I am making an app which consists of a navigation drawer and a recycler view inside it. However, the items inside the recycler view are not being displayed. I am not sure what I have been doing wrong. I will provide what I have. If you require anything please ask. Thanks
Adapter
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private LayoutInflater inflater;
List<Information> data = Collections.emptyList();
public Adapter(Context context, List<Information> data){
inflater=LayoutInflater.from(context);
this.data=data;
}
public MyViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
MyViewHolder holder= new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder viewHolder, int i) {
Information current = data.get(i);
viewHolder.title.setText(current.title);
viewHolder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listText);
icon = (ImageView) itemView.findViewById(R.id.listIcon);
}
}
}
Information
public class Information {
int iconId;
String title;
}
NavigationDrawerFragment
public class NavigationDrawerFragment extends Fragment {
private RecyclerView recyclerView;
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private View containerView;
private Adapter adapter;
private boolean mFromSavedInstanceState;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer= Boolean.valueOf(readFrompreferences(getActivity(),KEY_USER_LEARNED_DRAWER,"false"));
if(savedInstanceState!=null)
{
mFromSavedInstanceState=true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView=(RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new Adapter(getActivity(),getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<Information> getData(){
List<Information> data = new ArrayList<>();
int[] icons={R.drawable.thechefhat,R.drawable.thegrocerybasket,R.drawable.favouritesstar,R.drawable.supported};
String[] titles = {"Recipes","Ingredients","Favourites","Help"};
for(int i=0;i<titles.length&&i<icons.length;i++){
Information current = new Information();
current.iconId=icons[i];
current.title = titles[i];
data.add(current);
}
return data;
}
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);
if(!mUserLearnedDrawer){
mUserLearnedDrawer=true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER,mUserLearnedDrawer+"");
}
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);
if(slideOffset<0.6)
toolbar.setAlpha(1-slideOffset);
}
};
if(!mUserLearnedDrawer&&!mFromSavedInstanceState){
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static void saveToPreferences(Context context,String preferenceName, String preferenceValue){
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(preferenceName,preferenceValue);
editor.apply();
}
public static String readFrompreferences(Context context, String preferenceName, String defaultValue){
SharedPreferences sharedPreferences=context.getSharedPreferences(PREF_FILE_NAME,Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName,defaultValue);
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar)findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_Layout), toolbar);
}
#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);
}
}
custom_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:padding="8dp"
android:id="#+id/listIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="#drawable/supported"
/>
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dummy Text"
android:padding="8dp"
android:layout_gravity="center_vertical" />
</LinearLayout>
fragment_navigation_drawer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/lightPrimaryColor"
tools:context="com.example.ivan.tutorialapp.NavigationDrawerFragment">
<LinearLayout
android:id="#+id/containerDrawerImage"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="280dp"
android:layout_height="140dp"
android:layout_marginBottom="16dp"
android:src="#drawable/banner" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
custom_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:padding="8dp"
android:id="#+id/listIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="#drawable/supported"
/>
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dummy Text"
android:padding="8dp"
android:layout_gravity="center_vertical" />
</LinearLayout>
activity_main.xml
<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:id="#+id/drawer_Layout"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:layout_height="match_parent">
<RelativeLayout
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ivan.tutorialapp.MainActivity">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar">
</include>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/app_bar"
android:text="#string/hello_world"
/>
</RelativeLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.example.ivan.tutorialapp.NavigationDrawerFragment"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer">
</fragment>
</android.support.v4.widget.DrawerLayout>
You should change this method to return actual item count
#Override
public int getItemCount() {
return 0;
}
Related
I going to implement navigation drawer for one of my project. I am able to implement the same. However there is some lag in navigation drawer. Please Suggest.here is the image
Below is my code
Home_activity.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#drawable/image_login">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<RelativeLayout
android:id="#+id/searchBox"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_below="#+id/toolbar"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:background="#ffffff">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:text="Search a Property"
android:textColor="#b8bcc0"
android:textSize="14sp" />
<ImageView
android:id="#+id/imageView"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:src="#drawable/icon_search" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/box"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/searchBox"
android:gravity="center">
<ImageView
android:id="#+id/buyRentImage"
android:layout_width="110dp"
android:layout_height="110dp"
android:layout_marginBottom="2dp"
android:layout_marginRight="1dp"
android:src="#drawable/image_buy_rent" />
<ImageView
android:id="#+id/applyLoanImage"
android:layout_width="110dp"
android:layout_height="110dp"
android:layout_marginRight="3dp"
android:layout_toRightOf="#+id/buyRentImage"
android:src="#drawable/image_apply_for_loan" />
<ImageView
android:id="#+id/newProjectImage"
android:layout_width="110dp"
android:layout_height="110dp"
android:layout_marginRight="1dp"
android:layout_below="#+id/buyRentImage"
android:src="#drawable/image_new_projects" />
<ImageView
android:id="#+id/postPropertyImage"
android:layout_width="110dp"
android:layout_height="110dp"
android:layout_marginRight="3dp"
android:layout_below="#+id/buyRentImage"
android:layout_toRightOf="#+id/newProjectImage"
android:src="#drawable/image_post_my_property" />
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="70dp">
<RelativeLayout
android:id="#+id/homeiconImage"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"
android:background="#drawable/circle_blue"
android:gravity="center">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/icon_verified_property" />
</RelativeLayout>
<TextView
android:id="#+id/totalProperty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#id/homeiconImage"
android:text="300+"
android:textColor="#008dd5"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/totalProperty"
android:layout_marginLeft="25dp"
android:layout_toRightOf="#id/homeiconImage"
android:text="VARIFIED PROPERTIES"
android:textColor="#3d3e40"
android:textSize="16sp" />
<ImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="4dp"
android:src="#drawable/icon_next" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_alignParentBottom="true"
android:background="#008dd5" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.androidmobile.thanehomes.thanehomes.activities.home.NavigationFragment"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation" />
Home.java
public class Home extends AppCompatActivity implements NavigationFragment.FragmentDrawerListener {
Toolbar toolbar;
RelativeLayout box, searchBox;
ImageView buyRentImg, applyLoanImg, newProjectImg, postProjectImg;
TextView buyRentTxt, postPropertyTxt;
Menu myMenu;
int settleCount;
private NavigationFragment drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
settleCount = 1;
toolbar = (Toolbar) findViewById(R.id.toolbar);
searchBox = (RelativeLayout) findViewById(R.id.searchBox);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(" Thanehomes");
getSupportActionBar().setIcon(R.drawable.ic_logo);
box = (RelativeLayout) findViewById(R.id.box);
box.setRotation(45.0f);
searchBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent searchIntent = new Intent(Home.this, SearchProperty.class);
startActivity(searchIntent);
}
});
drawerFragment = (NavigationFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawerLayout), toolbar);
drawerFragment.setDrawerListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
myMenu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_menu, menu);
MenuItem item = myMenu.findItem(R.id.notification);
MenuItemCompat.setActionView(item, R.layout.update_count);
View count = myMenu.findItem(R.id.notification).getActionView();
TextView t = (TextView) count.findViewById(R.id.count);
if (settleCount < 1) {
t.setVisibility(View.GONE);
} else {
t.setVisibility(View.VISIBLE);
t.setText("" + settleCount);
}
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getApplicationContext(), "Click", Toast.LENGTH_SHORT).show();
Intent notificationIntent = new Intent(Home.this, NotificationList.class);
startActivity(notificationIntent);
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDrawerItemSelected(View view, int position) {
Toast.makeText(getApplicationContext(), position + "", Toast.LENGTH_SHORT).show();
}
}
NavigationFragment.java
public class NavigationFragment extends Fragment {
private static String TAG = NavigationFragment.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 NavigationFragment() {
}
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, 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.addDrawerListener(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.getChildAdapterPosition(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) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
If Navigation drawer is lagging while opening it means you are doing some resource intensive work in your navigation drawer.
If it lags while closing it means the fragment you are showing through navigation drawer is taking longer than navigation close time to draw itself.
Your problem is that you are doing some heavy task in the fragment you are opening through nav drawer.
Not completely sure but I got issues with lag at navigation drawer for some reason when I define support-screens and it is running in screen compatibility mode.
However it seemed to be caused by update of the burger menu icon by the ActionBarDrawerToggle.
May you can check if the problem vanishes when you provide an empty implementaion (supress also super-call) of onDrawerSlide
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
If it looks better you can try to perform that actions in a separate thread (if this UI features are necessary for you at all).
The first child in the layout is the listview for the main Activity UI in Navigation Drawer Layout . And I'm trying to display list-view with fragment and navigation drawer layout but list-view is not display in main Activity UI..Can someone help me how to show list.Thanks in advanced.
Here is my code
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The first child in the layout is for the main Activity UI-->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Side navigation drawer UI -->
<ListView
android:id="#+id/navList"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="left|start"
android:background="#ffeeeeee" />
</android.support.v4.widget.DrawerLayout>
MainActivity.java:
public class MainActivity extends ActionBarActivity {
private ListView mDrawerList ;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
Fragment fragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView) findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
fragment = new YourListFragment();
if (fragment != null)
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
}
private void addDrawerItems() {
String[] osArray = {"Android", "iOS", "Windows", "OS X", "Linux"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Display listview in fragment
public class YourListFragment extends Fragment {
int DR_CAMERA_REQUEST = 99999;
ListView allPostListView;
MyListAdapter adapter;
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.all_post_list_fragment, container, false);
allPostListView = (ListView)rootView.findViewById(R.id.listview_AllPost);
adapter = new MyListAdapter(getActivity().getBaseContext(),R.layout.all_post_row, bitmapArray);
allPostListView.setAdapter(adapter);
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == DR_CAMERA_REQUEST )
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
Log.e("photo ", " = " + photo);
bitmapArray.add(photo);
//imgProfilePic.setImageBitmap(photo);
}
}
}
Adapter class
class MyListAdapter extends ArrayAdapter {
Context context;
int layoutResourceId;
int DR_CAMERA_REQUEST = 99999;
ArrayList<Bitmap> bmp = new ArrayList<Bitmap>();
ProgressBar pBar;int fixedHeight = 220;
public MyListAdapter(Context context, int layoutResourceId , ArrayList<Bitmap> bitmapArray) {
super(context, layoutResourceId);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.bmp = bitmapArray;
}
#Override
public int getCount() {
return bmp.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View row, ViewGroup parent) {
final Holder holder;
if (row == null)
{
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
row = vi.inflate(R.layout.all_post_row, parent, false);
holder = new Holder();
holder.horizontalScrollView = (HorizontalScrollView) row.findViewById(R.id.hlist);
holder.lLinearLayout = (LinearLayout) row.findViewById(R.id.innerlay);
holder.imgBtn_Camera = (ImageView) row.findViewById(R.id.imgButton_Camera);
row.setTag(holder);
}
else
{
holder = (Holder) row.getTag();
}
LayoutInflater mInflater;
mInflater = LayoutInflater.from(getContext());
View cur_deal = mInflater.inflate(R.layout.horizontalitem, holder.lLinearLayout, false);
RelativeLayout rLayout = (RelativeLayout) cur_deal.findViewById(R.id.img_layout);
final ImageView imageView = (ImageView) cur_deal.findViewById(R.id.image_AllPost);
pBar = (ProgressBar) cur_deal.findViewById(R.id.pBar_AllPost);
holder.lLinearLayout.removeAllViews();
if(bmp.size() > 0)
{
int index = bmp.size() -1;
rLayout.getLayoutParams().height = fixedHeight;
Bitmap lastbitmap = bmp.get(index);
imageView.setImageBitmap(lastbitmap);
pBar.setVisibility(View.VISIBLE);
holder.lLinearLayout.addView(cur_deal);
}
//OnClickListener for camera button in the List
holder.imgBtn_Camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
((Activity)context).startActivityForResult(cameraIntent, DR_CAMERA_REQUEST);
Log.e("Camera", " Open");
}
});
return row;
}
final class Holder {
ImageView imgBtn_Camera;
LinearLayout lLinearLayout;
HorizontalScrollView horizontalScrollView;
}
}
Here is my all_post_row.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:orientation="vertical">
<HorizontalScrollView
android:id="#+id/hlist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:background="#android:color/white"
android:fillViewport="true"
android:measureAllChildren="false"
android:scrollbars="none">
<LinearLayout
android:id="#+id/innerlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#android:color/white"
android:orientation="horizontal"
>
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
<LinearLayout
android:id="#+id/buttonslayout"
android:layout_width="match_parent"
android:layout_height="26dp"
android:layout_marginTop="10dp"
android:background="#D8D8D8"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgButton_FoloowUp"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_marginLeft="20dp"
android:layout_weight="1"
android:contentDescription="desc"
android:src="#drawable/follow_up_grey" />
<ImageView
android:id="#+id/imgButton_Camera"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:contentDescription="desc"
android:src="#drawable/camera_grey" />
<ImageView
android:id="#+id/imgButton_RecordAudio"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:contentDescription="desc"
android:src="#drawable/recorder_gray" />
</LinearLayout>
</LinearLayout>
Here is horizontal.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/img_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:paddingLeft="1dp">
<ImageView
android:id="#+id/image_AllPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<ProgressBar
android:id="#+id/pBar_AllPost"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
Change
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
to:
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
i have a navigation drawer layout created from a NavigationDrawerFragment which extends fragment.I have added android:clickable="true" inside a linear layout in fragment_navigation_drawer as shown below.However i am stuck on how or where to add OnClick event in my NavigationDrawerFragment,or should i do it in another class which extends activity?Thanks in advance.
NavigationDrawerFragment.java:
public class NavigationDrawerFragment extends Fragment {
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private View containerView;
private AdapterClass adapter;
private RecyclerView recyclerView;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new AdapterClass(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<Information> getData() {
List<Information> data = new ArrayList<>();
int[] icons = {R.drawable.ic_menu_check, R.drawable.ic_menu_check, R.drawable.ic_menu_check, R.drawable.ic_menu_check};
String[] titles = {"Make up", "Lotions", "Deodorants", "Gels"};
for (int i = 0; i < titles.length && i < icons.length; i++) {
Information current = new Information();
current.iconId = icons[i];
current.title = titles[i];
data.add(current);
}
return data;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, 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);
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
}
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName, defaultValue);
}
}
fragment_navigation_drawer.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context="com.snappy.stevekamau.snappy.NavigationDrawerFragment">
<LinearLayout
android:id="#+id/containerDrawerImage"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<ImageView
android:layout_width="280dp"
android:layout_height="140dp"
android:background="#000000"
android:src="#drawable/header"></ImageView>
<LinearLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:clickable="true"
android:background="#drawable/linear_layout_clicked" >
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:src="#drawable/basket"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="0dp"
android:text="My Basket"
android:textStyle="bold"
android:textColor="#color/colorSecondaryText"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="13dp"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:textSize="16dp"
android:text="Categories" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_below="#id/containerDrawerImage"
android:id="#+id/drawerList"
android:layout_marginTop="5dp"
android:background="#ffffff"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
The obvious approach is to explicitly set a View.OnClickListener on the relevant widget (i.e. in onCreateView()):
layout.findViewById(R.id.linear).setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(...);
}
});
As far as your question goes:
where to add OnClick event in my NavigationDrawerFragment,or should i do it in another class which extends activity?
The listener really belongs in the class that inflates the layout file. If that's your NavigationDrawerFragment (which appear to be the case), then that's where the listener should live. From there on you can propagate the call elsewhere, but you can start an activity from a fragment just fine.
I am trying to implement a toggle button into the Navigation Drawer Project, that Android Studio can automatically generate.
In the end I want to have something like this ("Downloaded only"-Button):
Unfortunately I don't understand how to add a toggle button to the ListView of the NavDrawer. I could probably use one of the "Custom NavDrawer Libs" out there but I would like to understand the way Google proposes it with the auto generated example.
Any ideas on how to implement this into the default NavDrawer Project?
I would do something like this: instead of using a listview I would use an RecyclerView.
Then I create three different layout definitions for the label with icon, the divider and the label with optional switch. Your RecyclerView Adapter should extend Form RecyclerView.Adapter. For each of those three layouts you should create an own implementation of ViewHolder. Now you have to create several classes for the list items and one superclass for all of them. In your Adapter you have to override the getViewType method.
Tomorrow when I'm at work I could post some demo code for you.
Edit:
activity_main.xml
<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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="de.devhew.navigationdrawerexample.MainActivity">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:popupTheme="#style/AppTheme.Toolbar.Overflow"
app:theme="#style/AppTheme.Toolbar" />
<FrameLayout
android:id="#+id/main_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="de.devhew.navigationdrawerexample.drawer.NavigationDrawerFragment"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
MainActivity.java
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
List<NavDrawerEntry> drawerEntries = new ArrayList<>();
drawerEntries.add(new NavDrawerItemWithIcon("Home", R.drawable.app_generic));
drawerEntries.add(new NavDrawerItemWithIcon("People", R.drawable.app_generic));
drawerEntries.add(new NavDrawerItemWithIcon("Stuff", R.drawable.app_generic));
drawerEntries.add(new NavDrawerDivider());
drawerEntries.add(new NavDrawerItem("Settings"));
drawerEntries.add(new NavDrawerToggle("Wifi only"));
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.init((android.support.v4.widget.DrawerLayout) findViewById(R.id.drawer_layout),
toolbar, drawerEntries);
}}
NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
private View root;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private RecyclerView mRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
return root;
}
public void init(DrawerLayout drawerLayout, final Toolbar toolbar, List<NavDrawerEntry> drawerEntries) {
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();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mRecyclerView = (RecyclerView) root.findViewById(R.id.nav_list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setHasFixedSize(true);
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(getActivity(), drawerEntries);
mRecyclerView.setAdapter(adapter);
}}
NavigationDrawerAdapter.java
public class NavigationDrawerAdapter
extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<NavDrawerEntry> data;
private LayoutInflater inflater;
public NavigationDrawerAdapter(Context context, List<NavDrawerEntry> data) {
this.data = data;
this.inflater = LayoutInflater.from(context);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemLayoutView;
switch (viewType) {
case 0:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_item_with_icon, viewGroup, false);
ItemWithIconVH holder = new ItemWithIconVH(itemLayoutView);
return holder;
case 1:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_divider, viewGroup, false);
DividerVH dividerViewHolder = new DividerVH(itemLayoutView);
return dividerViewHolder;
case 2:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_item, viewGroup, false);
ItemVH itemViewHolder = new ItemVH(itemLayoutView);
return itemViewHolder;
case 3:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_toggle, viewGroup, false);
ToggleVH toggleViewHolder = new ToggleVH(itemLayoutView);
return toggleViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final NavDrawerEntry item = data.get(position);
if (item instanceof NavDrawerItemWithIcon) {
ItemWithIconVH viewHolder = (ItemWithIconVH) holder;
viewHolder.mTitle.setText(((NavDrawerItemWithIcon) item).getTitle());
viewHolder.mImageView.setImageResource(((NavDrawerItemWithIcon) item).getIconId());
}
if (item instanceof NavDrawerItem) {
ItemVH viewHolder = (ItemVH) holder;
viewHolder.mTitle.setText(((NavDrawerItem) item).getTitle());
}
if (item instanceof NavDrawerToggle) {
ToggleVH viewHolder = (ToggleVH) holder;
viewHolder.mTitle.setText(((NavDrawerToggle) item).getTitle());
viewHolder.mSwitch.setChecked(((NavDrawerToggle) item).isChecked());
}
}
#Override
public int getItemViewType(int position) {
if (data.get(position) instanceof NavDrawerItemWithIcon)
return 0;
if (data.get(position) instanceof NavDrawerDivider)
return 1;
if (data.get(position) instanceof NavDrawerItem)
return 2;
if (data.get(position) instanceof NavDrawerToggle)
return 3;
return -1;
}
#Override
public int getItemCount() {
return data.size();
}
class ItemWithIconVH extends RecyclerView.ViewHolder {
final TextView mTitle;
final ImageView mImageView;
public ItemWithIconVH(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.nav_item_title);
mImageView = (ImageView) itemView.findViewById(R.id.nav_item_image);
}
}
class DividerVH extends RecyclerView.ViewHolder {
public DividerVH(View itemView) {
super(itemView);
}
}
class ItemVH extends RecyclerView.ViewHolder {
final TextView mTitle;
public ItemVH(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.nav_item_title);
}
}
class ToggleVH extends RecyclerView.ViewHolder {
final TextView mTitle;
final Switch mSwitch;
public ToggleVH(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.nav_item_title);
mSwitch = (Switch) itemView.findViewById(R.id.nav_switch);
}
}}
Superclass for all NavDrawer Items:
public class NavDrawerEntry {}
Item without icon:
public class NavDrawerItem extends NavDrawerEntry {
private String title;
public NavDrawerItem(String title) {
this.setTitle(title);
}
public String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}}
Item with icon:
public class NavDrawerItemWithIcon extends NavDrawerEntry {
private String title;
private int iconId;
public NavDrawerItemWithIcon(String title, int iconId) {
this.setTitle(title);
this.setIconId(iconId);
}
public int getIconId() {
return iconId;
}
private void setIconId(int iconId) {
this.iconId = iconId;
}
public String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}}
Divider:
public class NavDrawerDivider extends NavDrawerEntry {}
Item with Switch:
public class NavDrawerToggle extends NavDrawerEntry {
private String title;
private boolean checked;
public NavDrawerToggle(String title) {
this.setTitle(title);
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}}
layout_nav_drawer_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true"
android:orientation="horizontal">
<TextView
android:id="#+id/nav_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:fontFamily="sans-serif"
android:textColor="#000"
android:textSize="16sp" /></LinearLayout>
layout_nav_drawer_item_with_icon.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true"
android:orientation="horizontal">
<ImageView
android:id="#+id/nav_item_image"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:src="#drawable/app_generic" />
<TextView
android:id="#+id/nav_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:fontFamily="sans-serif"
android:text="Verbundene Geräte"
android:textColor="#000"
android:textSize="16sp" /></LinearLayout>
layout_nav_drawer_divider.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#ddd"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp" /></LinearLayout>
layout_nav_drawer_toggle.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true">
<TextView
android:id="#+id/nav_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:fontFamily="sans-serif"
android:text="Verbundene Geräte"
android:textColor="#000"
android:textSize="16sp" />
<Switch
android:id="#+id/nav_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="16dp" /></RelativeLayout>
fragment_navigation_drawer.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="280dp"
android:layout_height="match_parent"
android:background="#eee"
tools:context="de.vacom.hew.materialdemo.NavigationDrawerFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#color/primaryColor"
android:elevation="3dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/nav_app_icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="55dp"
android:src="#drawable/app_generic" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="64dp"
android:fontFamily="sans-serif-medium"
android:text="Demo App"
android:textColor="#eee"
android:textSize="18sp" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/nav_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout></FrameLayout>
I have been making an app that uses a recycler view in a navigation drawer. Why the contents of the recycler view are not showing up. The view is definitely there as I can see the scroll shadows. I am not sure what I have done wrong, as the app does not crash when it is run.
Navigation Drawer Fragment:
public class NavigationDrawerFragment extends android.support.v4.app.Fragment {
public static final String PREF_FILE_NAME = "testPref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private RecyclerView mRecyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private View containerView;
private Boolean mUserLearnedDrawer;
private Boolean mFromSavedInstanceState;
private DrawerAdapter adapter;
public NavigationDrawerFragment() {
mFromSavedInstanceState = false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null){
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mRecyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new DrawerAdapter(getActivity(), getData());
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<DrawerRow> getData(){
List<DrawerRow> data = new ArrayList<>();
int icons[] = {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};
String titles[] = {"Link 1","Link 2","Link 3","Link 4"};
for (int i = 0 ; i < titles.length && i < icons.length; i++){
DrawerRow current = new DrawerRow();
current.iconId = icons[i];
current.title = titles[i];
data.add(current);
}
return data;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawerOpen, R.string.drawerClosed){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if(!mUserLearnedDrawer){
mUserLearnedDrawer = true;
saveToPreferences(getActivity(),KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer+"");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
};
if(!mUserLearnedDrawer && !mFromSavedInstanceState){
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public void saveToPreferences(Context context, String prefName, String prefValue){
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = sharedPreferences.edit();
mEditor.putString(prefName, prefValue);
mEditor.apply();
}
public static String readFromPreferences(Context context, String prefName, String defaultValue){
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(prefName,defaultValue);
}
}
Adapter:
public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.MyViewHolder>{
private LayoutInflater inflator;
List<DrawerRow> data = Collections.EMPTY_LIST;
public DrawerAdapter(FragmentActivity activity, List<DrawerRow> data) {
inflator = LayoutInflater.from(activity);
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = inflator.inflate(R.layout.nav_drawer_row , viewGroup,false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder viewHolder, int i) {
DrawerRow current = data.get(i);
viewHolder.title.setText(current.title);
viewHolder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView icon;
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
icon = (ImageView) itemView.findViewById(R.id.list_icon);
title = (TextView) itemView.findViewById(R.id.list_text);
}
}
}
Drawer Row:
public class DrawerRow {
int iconId;
String title;
}
Layout:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawerLayout">
<!--Main Content -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text" />
</LinearLayout>
<!--Nav Drawer -->
<fragment
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="uk.co.clickcomputing.hhscweatherstation.NavigationDrawerFragment"
android:id="#+id/fragment_navigation_drawer"/>
</android.support.v4.widget.DrawerLayout>
Drawer Row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:padding="#dimen/list_padding"
android:id="#+id/list_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="#drawable/ic_launcher"/>
<TextView
android:padding="#dimen/list_padding"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="New Text"
android:id="#+id/list_text" />
</LinearLayout>
Navigation Drawer Fragment Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#eee"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_marginBottom="8dp"
android:contentDescription="#string/nav_drawer_img_desciption"
android:scaleType="centerCrop"
android:src="#drawable/nav_drawer" />
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/drawerList">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
The issue is that you are returning the item count as 0 which tells that there is no rows to show. You should return the size of the List as shown below.
#Override
public int getItemCount() {
return data.size();
}
Replace following line
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
with
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setAdapter(adapter);
I agree that you need to return the correct item number but I think you might have a problem with setting the recycler view's height to wrap_content as well. I found this link very helpful. Hope it helps.
Make sure RecyclerView parent container width not set as WrapContent
#Override
public int getItemCount() {
return data.size();
}
and layout height in your row is android:layout_height="match_parent" but must be android:layout_height="wrap_content"
Adding app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" to the RelativeLayout solved my problem.
<androidx.recyclerview.widget.RecyclerView
...
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
...
/>
Check for your RecyclerView's width and height attributes, if they are set to wrap content, change it to match parent or constraint your view in some specific area.
Also check for Parent view's width attribute, if it's set to wrap content change it to match parent as well.
I have given static height and match_parent. It works for my Example I haved added it in nested recyclerview.
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/new_store_page_phoneNumber_rv"
android:layout_width="match_parent"
android:layout_height="50dp"
android:scrollIndicators="bottom"
android:fadeScrollbars="false"
android:layout_gravity="center_vertical"
app:adapter="#{adapter}"
android:focusable="true"
android:focusableInTouchMode="true"
android:clickable="true"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbars="none"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:orientation="horizontal" />
If you are fetching data from the network, make sure you are reloading/refreshing your adapter in the UI thread. This was the solution for me.
The common problem is that you might have forgotten to set your recyclerview with adapter
example in kotlin
adapter= CartAdapter(this)
val linearLayoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
binding.productCartRecycler.layoutManager = linearLayoutManager
binding.productCartRecycler.adapter = adapter