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).
Related
I'm using Material Navigation Drawer, What i want to do is the following :
Having A Header in the Navigation Drawer ( Background With App Icon ) .
Section Under The Header .
Navigation-able fragments under the section name .
My Problem :
Header isn't showing at all .
Navigation drawer isn't on top, it's like a regular navigation drawer .
First section gets repeated, for more simplify, the first instance of it stay in position while scrolling, the second (repeated) move according to scroll .
Code :
Adapter (Sample of it) :
public class NavDrawerAdapter extends
RecyclerView.Adapter<NavDrawerAdapter.ViewHolder> {
private List<NavItem> mData;
private NavDrawerCallback mNavDrawerCallbacks;
private NavDrawerFragment mContext;
public NavDrawerAdapter(List<NavItem> data, NavDrawerFragment context) {
mData = data;
mContext = context;
}
#Override
public NavDrawerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup,
int i) {
if (i == 0) {
return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.drawer_top, viewGroup, false));
} else if (i == 1) {
return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.drawer_section, viewGroup, false));
}
View v = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.drawer_row, viewGroup, false);
return new ViewHolder(v);
}
#Override
public int getItemViewType(int position) {
if (mData.get(position).getType() == NavItem.TOP){
return 0;
} else if (mData.get(position).getType() == NavItem.SECTION) {
return 1;
} else {
return 2;
}
}
Navigation Fragment :
public class NavDrawerFragment extends Fragment implements NavDrawerCallback {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private NavDrawerCallback mCallbacks;
private RecyclerView mDrawerList;
private View mFragmentContainerView;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private int mCurrentSelectedPosition;
private List<NavItem> mConfiguration;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.drawer_fragment, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavItem> NavItems = getConfiguration();
NavDrawerAdapter adapter = new NavDrawerAdapter(NavItems, NavDrawerFragment.this);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition, NavItems.get(mCurrentSelectedPosition));
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavDrawerCallback) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavDrawerCallback.");
}
}
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mActionBarDrawerToggle;
}
public void setActionBarDrawerToggle(ActionBarDrawerToggle actionBarDrawerToggle) {
mActionBarDrawerToggle = actionBarDrawerToggle;
}
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu();
}
};
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
//TODO This works (hides the drawer if there is only 1 item), but makes settings and favorites unreachable
boolean newDrawer = getResources().getBoolean(R.bool.newdrawer);
if (newDrawer == false && getConfiguration().size() == 1){
mActionBarDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
if (newDrawer == true && getConfiguration().size() == 2){
mActionBarDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
}
public void openDrawer() {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
void selectItem(int position, NavItem item) {
//If on start, item is section, change it.
if (item.getType() == NavItem.SECTION || item.getType() == NavItem.TOP){
position = position + 1;
item = getConfiguration().get(position);
selectItem(position, item);
return;
}
mCurrentSelectedPosition = position;
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position, item);
}
((NavDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onNavigationDrawerItemSelected(int position, NavItem item) {
//TODO we can also call this method here, but that won't set an initial item.
//mCallbacks.onNavigationDrawerItemSelected(position, item);
if (item.getType() != NavItem.SECTION){
selectItem(position, item);
}
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
public void setDrawerLayout(DrawerLayout drawerLayout) {
mDrawerLayout = drawerLayout;
}
private List<NavItem> getConfiguration(){
if (null == mConfiguration){
mConfiguration = Config.configuration();
boolean newDrawer = getResources().getBoolean(R.bool.newdrawer);
if (newDrawer == true){
mConfiguration.add(0, new NavItem("Header", NavItem.TOP));
}
}
return mConfiguration;
}
}
Styles :
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="drawerArrowStyle">#style/DrawerArrowStyle</item>
<item name="windowActionModeOverlay">true</item>
<item name="android:textColor">#color/black</item>
<item name="android:windowBackground">#color/myWindowBackground</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">#android:color/white</item>
</style>
Drawer Fragment xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:clickable="true"
android:focusableInTouchMode="true"
android:scrollbars="vertical"
android:focusable="true"
android:layout_height="match_parent"
android:background="#color/myDrawerBackground"/>
Drawer Section 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="wrap_content"
android:orientation="vertical" >
<View
android:layout_width="fill_parent"
android:layout_height="0.5dp"
android:background="#color/light_gray" />
<TextView
android:id="#+id/section_name"
android:textAllCaps="false"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="10dp"
android:layout_marginEnd="16dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="10dp"
android:drawablePadding="16dp"
android:gravity="center_vertical"
android:textAppearance="#style/TextAppearance.AppCompat.Title"
android:textColor="#color/dim_gray"
android:textSize="14sp" />
</LinearLayout>
Drawer Top :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:src="#drawable/drawer_header"
android:adjustViewBounds="true"
android:maxHeight="195dp"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:gravity="center"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:background="#drawable/drawer_top_gradient"
android:paddingLeft="20dp"
android:paddingTop="20dp"
android:paddingBottom="10dp"
android:paddingRight="10dp"
android:text="#string/app_name"
android:textSize="22sp"
android:textAppearance="#style/TextAppearance.AppCompat.Headline"
android:textColor="#color/white"
android:paddingStart="20dp"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:paddingEnd="10dp" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Solved, by building the project from scratch.
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 am following this example for navigation drawer. Now I am able to display text and I also set icons, but icon is not visible. Can any one help me with that? What is the issue with that code:
FragmentDrawer.java
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 = null;
private FragmentDrawerListener drawerListener;
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);
// drawer labels
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) {
// 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) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:id="#+id/icon"
/>
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:paddingLeft="30dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textSize="15dp"
android:text="Profile"
/>
</RelativeLayout>
I used this code to solve this problem please check it hopefully it will work.
Make a new project or add it to your existing project.
MainActivity.java
public class MainActivity extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.inbox:
Toast.makeText(getApplicationContext(),"Inbox Selected",Toast.LENGTH_SHORT).show();
ContentFragment fragment = new ContentFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
return true;
// For rest of the options we just show a toast on click
case R.id.starred:
Toast.makeText(getApplicationContext(),"Stared Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.sent_mail:
Toast.makeText(getApplicationContext(),"Send Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.drafts:
Toast.makeText(getApplicationContext(),"Drafts Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.allmail:
Toast.makeText(getApplicationContext(),"All Mail Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.trash:
Toast.makeText(getApplicationContext(),"Trash Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.spam:
Toast.makeText(getApplicationContext(),"Spam Selected",Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#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);
}
}
ContentFragment.java
public class ContentFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.content_fragment,container,false);
return v;
}
}
In your XML Layouts add these files
header.xml
<?xml version="1.0" encoding="utf-8"?>
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="76dp"
android:layout_height="76dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:src="#drawable/profile"
app:border_color="#FF000000" />
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/email"
android:layout_alignLeft="#+id/profile_image"
android:layout_alignStart="#+id/profile_image"
android:gravity="left"
android:paddingBottom="4dp"
android:text="Umer Kiani"
android:textColor="#FFF"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/username"
android:layout_alignParentBottom="true"
android:layout_alignStart="#+id/username"
android:layout_marginBottom="8dp"
android:gravity="left"
android:text="umerkiani#gmail.com"
android:textColor="#fff"
android:textSize="14sp" />
</RelativeLayout>
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="#dimen/abc_action_bar_default_height_material"
android:background="#color/PrimaryColor"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
>
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar"
/>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer"
/>
</android.support.v4.widget.DrawerLayout>
use this code to change navigation icon
drawerToggle.setDrawerIndicatorEnabled(false);
toolbar.setNavigationIcon(R.drawable.ic_nav);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.openDrawer(Gravity.LEFT);
}
});
drawerToggle.syncState();
i hope this works for you. please change your setUp function like this.
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
//add here this code
toolbar.setNavigationIcon(R.drawable.iv_menu);
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();
}
});
}
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;
}
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.