Navigation Drawer does not open when I use ViewPager as Fragment - android

I had scenario where NavigationDrawer does not popup when I use ViewPager as Fragment which itself is launched when I click one of the NavigationDrawer items.I am using material design where both my NavigationDrawer and ViewPager both are fragments. My Code is as b
package com.andr.viewpager;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.andr.navdrawerdemo.FragmentDrawer;
import com.andr.navdrawerdemo.FriendsFragment;
import com.andr.navdrawerdemo.HomeFragment;
import com.andr.navdrawerdemo.MessagesFragment;
import com.andr.navdrawerdemo.R;
public class ViewPagerFagment extends Fragment{
private ViewPager mPager;
private View view;
private PagerAdapter mPagerAdapter;
private static final int NUM_PAGES = 3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_screen_slide, container, false);
mPager = (ViewPager)view.findViewById(R.id.pager);
mPager.setPageTransformer(true, new DepthPageTransformer());
mPagerAdapter = new ScreenSlidePagerAdapter(getActivity().getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
return view;
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0: return new MessagesFragment();
case 1: return new HomeFragment();
case 2: return new FriendsFragment();
default: return new FriendsFragment();
}
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onResume() {
super.onResume();
}
}
NavigationDrawer fragment:
package com.andr.navdrawerdemo;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import com.andr.adapter.NavigationDrawerAdapter;
import com.andr.model.NavDrawerItem;
import com.andr.navdrawerdemo.R;
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private com.andr.adapter.NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
My Individual Fragments:
package com.andr.navdrawerdemo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.andr.navdrawerdemo.R;
public class FriendsFragment extends Fragment {
public FriendsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_friends, container, false);
}
}
package com.andr.navdrawerdemo;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.andr.navdrawerdemo.R;
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
package com.andr.navdrawerdemo;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.andr.navdrawerdemo.R;
public class MessagesFragment extends Fragment {
public MessagesFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_messages, container, false);
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
my mainActivity
package com.andr.navdrawerdemo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.andr.navdrawerdemo.R;
import com.andr.viewpager.ViewPagerFagment;
//http://www.androidhive.info/2015/04/android-getting-started-with-material-design/
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);*/
initializeSlidingMenu();
}
public void initializeSlidingMenu(){
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
case 3:
fragment = new ViewPagerFagment();
title = getString(R.string.title_slider);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
// my layouts
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
tools:context="com.andr.navdrawerdemo.MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.andr.navdrawerdemo.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
Viewpager layout
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Can anyone help me y my slidingmenu does n't popup in ViewPAger fragment

I believe the ViewPager should be inside the main layout. I'm still struggling with making this work 100%, but by doing:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="thehighestprimenumber.com.losprincipios.ChapterActivity">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout android:id="#+id/containerBox" android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.view.ViewPager>
<ListView android:id="#+id/drawer"
...
/>
</android.support.v4.widget.DrawerLayout>
This way the navigationDrawer opens.
My problem is, when I click on an item on the Navigation Drawer, the fragment doesn't update.
if you know how to solve this, you'd make my day =)

Related

How to set onclick listener for tabView with listed items and move to a new Activity

Here I created a simple Tablayout with some options under it. When clicked on particular item the application should open another activity containing the particular class. Could Some one please help how to write the code for item onclick listener .Here I am attaching the code of my TabLayout java class and my versionModel java class with xml included. I am also attaching the screenshot of the app. So as in the screenshot when i click on the Topwear , page containing Topwear should open.
TabAnimationActivity.java
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.suleiman.material.R;
import com.suleiman.material.adapter.SimpleRecyclerAdapter;
import com.suleiman.material.model.VersionModel;
import java.util.ArrayList;
import java.util.List;
public class TabAnimationActivity extends AppCompatActivity {
SimpleRecyclerAdapter adapter;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_animation);
final Toolbar toolbar = (Toolbar) findViewById(R.id.tabanim_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ViewPager viewPager = (ViewPager) findViewById(R.id.tabanim_viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabanim_tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
showToast("One");
break;
case 1:
showToast("Two");
break;
case 2:
showToast("Three");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment(getResources().getColor(R.color.accent_material_light)), "Men");
adapter.addFrag(new DummyFragment(getResources().getColor(R.color.ripple_material_light)), "Women");
adapter.addFrag(new DummyFragment(getResources().getColor(R.color.button_material_dark)), "Kids");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tab_switch, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_switch:
Intent intent = new Intent(TabAnimationActivity.this, TabsHeaderActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public static class DummyFragment extends Fragment {
int color;
SimpleRecyclerAdapter adapter;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
List<String> list = new ArrayList<String>();
for (int i = 0; i < VersionModel.data.length; i++) {
list.add(VersionModel.data[i]);
}
adapter = new SimpleRecyclerAdapter(list);
recyclerView.setAdapter(adapter);
return view;
}
}
}
VersionModel.java
public class VersionModel {
public String name;
public static final String[] data = {"Topwear", "Bottomwear", "Footwear",
"Sports wear", "Innerwear &Sleepwear", "SmartWearables",
"Watches", "Accessories", "PersonalGrooming", "T-Shirts"};
VersionModel(String name){
this.name=name;
}
}
dummy_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dummyfrag_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_material_light">
<android.support.v7.widget.RecyclerView
android:id="#+id/dummyfrag_scrollableview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
I hope This may give you an idea on Recyclerview OnItemClick.
RecyclerView recyclerView = (RecyclerView)v.findViewById(R.id.dummyfrag_scrollableview);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(llm);
recyclerView.setHasFixedSize(true); // to improve performance
recyclerView.setAdapter(new YourRecylerAdapter());
recyclerView.addOnItemTouchListener( new RecyclerClickListener(getContext(), new RecyclerClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(getActivity(),
YourDetailedActivity.class);
startActivity(intent);
}}));
return v;

Adding icon with each row of menu in Navigation Drawer

i'm new to android and i'm trying to add icon in each row of menu in Navigation Drawer using
Adapter Class:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.ash.light.R;
import java.util.Collections;
import java.util.List;
import model.NavDrawerItem;
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data= Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data){
this.context=context;
inflater=LayoutInflater.from(context);
this.data=data;
}
public void delete(int position){
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view=inflater.inflate(R.layout.nav_row_drawer, parent, false);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
NavDrawerItem current=data.get(position);
holder.title.setText(current.getTitle());
holder.icon.setImageResource(current.getIcon());
}
#Override
public int getItemCount(){
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView title;
ImageView icon;
public MyViewHolder(View itemView){
super(itemView);
title=(TextView) itemView.findViewById(R.id.title);
icon=(ImageView) itemView.findViewById(R.id.rowIcon);
}
}
}
and with model:
public class NavDrawerItem {
private boolean shownotify;
private String title;
private int icon;
public NavDrawerItem(){
}
public NavDrawerItem(boolean shownotify, String title, int icon){
this.shownotify=shownotify;
this.title=title;
this.icon=icon;
}
public boolean isShowNotify(){
return shownotify;
}
public void setShowNotify(boolean shownotify){
this.shownotify=shownotify;
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title=title;
}
public int getIcon(){
return icon;
}
public void setIcon(int icon){
this.icon=icon;
}
}
using FragmentDrawer class:
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.widget.Toolbar;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import adapter.NavigationDrawerAdapter;
import model.NavDrawerItem;
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles=null;
private static int[] icons;
private FragmentDrawerListener drawerListener;
// private OnFragmentInteractionListener mListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener){
this.drawerListener=listener;
}
public static List<NavDrawerItem> getData(){
List<NavDrawerItem> data=new ArrayList<>();
for(int i=0;i<titles.length;i++){
NavDrawerItem navItem=new NavDrawerItem();
navItem.setTitle(titles[i]);
navItem.setIcon(icons[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
titles=getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
icons=getActivity().getResources().getIntArray(R.array.nav_drawer_icons);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout= inflater.inflate(R.layout.fragment_nav_drawer, container, false);
recyclerView=(RecyclerView) layout.findViewById(R.id.drawerlist);
adapter=new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener(){
#Override
public void onClick(View view, int position){
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position){
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar){
containerView=getActivity().findViewById(fragmentId);
mDrawerLayout=drawerLayout;
mDrawerToggle=new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerOpened(View drawerView){
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideoffset){
super.onDrawerSlide(drawerView, slideoffset);
toolbar.setAlpha(1-(slideoffset/2));
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
this.clickListener=clickListener;
gestureDetector=new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e){
return true;
}
#Override
public void onLongPress(MotionEvent e){
View child=recyclerView.findChildViewUnder(e.getX(), e.getY());
if(child!=null && clickListener!=null){
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e){
View child=rv.findChildViewUnder(e.getX(), e.getY());
if(child!=null && clickListener!=null && gestureDetector.onTouchEvent(e)){
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e){
}
}
public interface FragmentDrawerListener{
public void onDrawerItemSelected(View view, int position);
}
}
and MainActivity:
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
//import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar mtoolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mtoolbar=(Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mtoolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment=(FragmentDrawer) getSupportFragmentManager().findFragmentById(R.id.fragment_nav_drawer);
drawerFragment.setUp(R.id.fragment_nav_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mtoolbar);
drawerFragment.setDrawerListener(this);
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position){
displayView(position);
}
private void displayView(int position){
Fragment fragment=null;
String title=getString(R.string.app_name);
switch (position){
case 0:
fragment=new HomeFragment();
title="Home";
break;
case 1:
fragment=new AmcFragment();
title="Amc Wise";
break;
case 2:
fragment=new AssetFragment();
title="Asset Class";
break;
case 3:
fragment=new FolioFragment();
title="Folio Based Report";
break;
case 4:
fragment=new FdFragment();
title="FD Wise";
break;
case 5:
fragment=new NewsFragment();
title="News and Updates";
break;
case 6:
fragment=new CalculatorFragment();
title="Financial Calculator";
break;
default:
break;
}
if(fragment!=null){
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.body_container, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
}
}
}
i not getting icon with menu items, rest everything is working fine. i know there are various other methods to get the icons with navigation bar menu, but
i want to get icons using these classes only (if possible),with minor editing.
Please help me out..

How to add Tabhost in Navigation Drawer

In my app I am using navigation drawer from this tutorial http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
Now I am trying to add tabhost with fragment,but its not working
it shows error here tabss.setViewPager(mViewPager);
Cannot resolve method setviewpager(android.support.v4.view.viewpager)
public class All_Product_Details extends Fragment {
private TabHost mTabHost;
private ViewPager mViewPager;
private YourAdapter mTabsAdapter;
private Button descr;
private TextView general_desc;
private TextView short_desc;
private TextView full_desc;
private Button btn_add_to_cart;
public All_Product_Details(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.all_product_detais, container, false);
mViewPager = (ViewPager)rootView.findViewById(R.id.viewpager);
mTabsAdapter= new YourAdapter(getFragmentManager());
mViewPager.setAdapter(mTabsAdapter);
TabWidget tabss = (TabWidget)rootView.findViewById(R.id.tabs);
tabss.setViewPager(mViewPager);
general_desc=(TextView)rootView.findViewById(R.id.general_desc);
short_desc=(TextView)rootView.findViewById(R.id.short_desc);
full_desc=(TextView)rootView.findViewById(R.id.full_desc);
btn_add_to_cart=(Button)rootView.findViewById(R.id.btn_addtocart);
btn_add_to_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Add_to_cart tf = new Add_to_cart();
android.support.v4.app.FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
short_desc.setVisibility(View.GONE);
full_desc.setVisibility(View.GONE);
descr=(Button)rootView.findViewById(R.id.all_prod_description);
descr.setBackgroundResource(R.drawable.hidebackground);
descr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (flag == 0) {
descr.setBackgroundResource(R.drawable.showbackground);
//lnrallbtns.setVisibility(View.GONE);
general_desc.setVisibility(View.GONE);
flag++;
} else {
descr.setBackgroundResource(R.drawable.hidebackground);
// lnrallbtns.setVisibility(View.VISIBLE);
general_desc.setVisibility(View.VISIBLE);
short_desc.setVisibility(View.GONE);
full_desc.setVisibility(View.GONE);
flag = 0;
}
}
});
return rootView;
}
public class YourAdapter extends FragmentStatePagerAdapter {
private String[] titles = { "Item 1", "Item 2", "Item 3" };
public YourAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch(i){
case 0:{
return new FragementA();
}case 1:{
return new FragmentB();
}case 2:{
return new FragmentC();
}
}
}
#Override
public int getCount() {
return titles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
I found and referred an awsm example called Balaji-K13 .
You can add whatever your list in here like:
Inside MainActivity.java
package com.webileapps.navdrawer;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class MainActivity extends SherlockFragmentActivity {
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
break;
}
case R.id.action_contact:
// QuickContactFragment dialog = new QuickContactFragment();
// dialog.show(getSupportFragmentManager(), "QuickContactFragment");
// return true;
}
return super.onOptionsItemSelected(item);
}
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(int position) {
switch (position) {
case 0:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content,
PageSlidingTabStripFragment.newInstance(),
PageSlidingTabStripFragment.TAG).commit();
break;
default:
SherlockFragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.add(R.id.content, fragment).commit();
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
Inside PageSlidingTabStripFragment.java
package com.webileapps.navdrawer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
import com.astuetz.PagerSlidingTabStrip;
public class PageSlidingTabStripFragment extends Fragment {
public static final String TAG = PageSlidingTabStripFragment.class
.getSimpleName();
public static PageSlidingTabStripFragment newInstance() {
return new PageSlidingTabStripFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.pager, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) view
.findViewById(R.id.tabs);
ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
private final String[] TITLES = { "Categories", "Home", "Top Paid",
"Top Free" };
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public SherlockFragment getItem(int position) {
return SuperAwesomeCardFragment.newInstance(position);
}
}
}
Inside PlanetFragment.java
package com.webileapps.navdrawer;
import java.util.Locale;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.actionbarsherlock.app.SherlockFragment;
public class PlanetFragment extends SherlockFragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container,
false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(
planet.toLowerCase(Locale.getDefault()), "drawable",
getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image))
.setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
And finally SuperAwesomeCardFragment.java
package com.webileapps.navdrawer;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class SuperAwesomeCardFragment extends SherlockFragment{
private static final String ARG_POSITION = "position";
private int position;
public static SuperAwesomeCardFragment newInstance(int position) {
SuperAwesomeCardFragment f = new SuperAwesomeCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
FrameLayout fl = new FrameLayout(getActivity());
fl.setLayoutParams(params);
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources()
.getDisplayMetrics());
TextView v = new TextView(getActivity());
params.setMargins(margin, margin, margin, margin);
v.setLayoutParams(params);
v.setLayoutParams(params);
v.setGravity(Gravity.CENTER);
v.setBackgroundResource(R.drawable.background_card);
v.setText("CARD " + (position + 1));
fl.addView(v);
return fl;
}
}
Hope this Helped :)

How can I manually set icons for each fragments in navigation drawer recycler view?

I followed android hive tutorials to make this navigation drawer. This is my code,
MainActivity.Java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import androidhive.info.materialdesign.AddNewBiller;
import androidhive.info.materialdesign.R;
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
int ICONS[] = {R.drawable.ic_dashboard,R.drawable.ic_action,R.drawable.ic_quick};
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_add) {
startActivity(new Intent(this, AddNewBiller.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
FragmentDrawer
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import androidhive.info.materialdesign.R;
import androidhive.info.materialdesign.adapter.NavigationDrawerAdapter;
import androidhive.info.materialdesign.model.NavDrawerItem;
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
NavigationDrawerAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
import androidhive.info.materialdesign.R;
import androidhive.info.materialdesign.model.NavDrawerItem;
/**
* Created by Ravi Tamada on 12-03-2015.
*/
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
}
}
}
Layout file- fragment_navigation_drawer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/navigationBarColor">
<RelativeLayout
android:id="#+id/nav_header_container"
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_alignParentTop="true"
android:background="#android:color/white">
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:src="#drawable/ic_profile"
android:scaleType="fitCenter"
android:id="#+id/imageView2"
android:layout_above="#+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:background="#drawable/logo"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Username"
android:textColor="#color/colorPrimaryDark"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imageView2"
android:layout_toEndOf="#+id/imageView2"
android:textStyle="italic"
android:textSize="#dimen/abc_text_size_small_material" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/nav_header_container"
android:layout_marginTop="15dp"
android:divider="#FFFFFF"
android:dividerHeight="1dp"
/>
</RelativeLayout>
When I try to change them it is making changes for all the fragments. Also it would be great if any of you could help me with adding separators in between each fragments.
you have not set any images for the imageView present in your nav_drawer_row.xml file. Make sure you are setting image in onBindViewHolder method.

Android: tabs with swipe not showing listfragment

I'm dealing with this tutorial: http://www.lucazanini.eu/2012/android/tabs-and-swipe-views/?lang=en .
The problem is that if I set as layout of the tab a simple static layout, like this (as the tutorial does), everything works fine:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/body1" />
</LinearLayout>
But I need the tab to be a ListFragment, and the matter is that my ListFragment shows nothing at all.
Here is the code. Don't desperate: I put lots of code but I think you will probably just need to look at the classes SongsFragment and SongsListAdapter (well, I am not sure because I were it I would not write here, however I suppose it because with a static layout everything works fine!)
EDIT: I post just one listfragment in the exemple, however it seems that every listfragment has the same issue
EDIT: probably the problem is that I need to use a method to show the fragment when the tab is selected
THANKS A LOT
Activity:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class PlayerActivity extends FragmentActivity implements
ActionBar.TabListener {
CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCollectionPagerAdapter = new CollectionPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select
// the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if
// we have a reference to the Tab.
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mCollectionPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mCollectionPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// TODO Auto-generated method stub
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
SongsFragment
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class SongsFragment extends ListFragment {
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class SongsFragment extends ListFragment {
List<String[]> songs;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
songs = SongsDataSource.getInstance().getAllSongs();
List<String[]> values = new ArrayList<String[]>();
if (songs.size() == 0) {
values.add(new String[] { "No files found", "Try to update your database", "" });
}
for (String[] song : songs) {
values.add(new String[] { song[1], song[2], song[0] });
}
SongsListAdapter adapter = new SongsListAdapter(getActivity().getApplicationContext(),
R.layout.songs, R.id.songsFragment_titleTextView,R.id.songsFragment_artistTextView, values);
setListAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.songs, container, false);
return view;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
}
}
SongsListAdapter
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SongsListAdapter extends ArrayAdapter<List<String[]>> {
private final Context context;
private final List<String[]> values;
private final Integer listViewId;
private final Integer titleTextViewId;
private final Integer artistTextViewId;
public SongsListAdapter(Context context, Integer listViewId, Integer titleTextViewId,
Integer artistTextViewId, List values) {
super(context, listViewId, values);
this.context = context;
this.listViewId = listViewId;
this.values = values;
this.titleTextViewId = titleTextViewId;
this.artistTextViewId = artistTextViewId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(listViewId, parent, false);
TextView titleView = (TextView) rowView.findViewById(titleTextViewId);
TextView artistView = (TextView) rowView.findViewById(artistTextViewId);
titleView.setText(values.get(position)[0]);
artistView.setText(values.get(position)[1]);
return rowView;
}
}
PagerAdapter
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class CollectionPagerAdapter extends FragmentPagerAdapter {
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return MyApplication.getInstance().infoFragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
String tabLabel = null;
if(0 <= position && position < MyApplication.getInstance().infoFragments.length) {
tabLabel = MyApplication.getInstance().infoFragments[position].getLabel();
}
return tabLabel;
}
}
TabFragment class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A fragment that launches other parts of the demo application.
*/
public class TabFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
if(0 <= position && position < MyApplication.getInstance().infoFragments.length) {
tabLayout = MyApplication.getInstance().infoFragments[position].getLayout();
}
View rootView = inflater.inflate(tabLayout, container, false);
return rootView;
}
}
MyApplication class
import android.app.Application;
public class MyApplication extends Application {
//SIGLETON DECLARATION
private static MyApplication mInstance = null;
public static MyApplication getInstance() {
if (mInstance == null) {
mInstance = new MyApplication();
}
return mInstance;
}
public static InfoFragment[] infoFragments = new InfoFragment[] {
new InfoFragment("Songs", R.layout.songs)
};
public static class InfoFragment {
private String label;
private int layout;
public InfoFragment(String label, int layout) {
this.label = label;
this.layout = layout;
}
public String getLabel() {
return label;
}
public int getLayout() {
return layout;
}
}
}
Oh, it seems like you never actually return your SongsFragment in your getItem() method. It actually seems like you never use it!
#Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}

Categories

Resources