BaseActivity for Navigation - android

I'm building a base activity for navigation and want something flexible so the Activity dictates to the Base Activity which layout to inflate.
I have the following
public abstract class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private int mLayoutRes;
protected void setLayout(int layoutRes) {
mLayoutRes = layoutRes;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(mLayoutRes);
// Layout implements toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null){
setSupportActionBar(toolbar);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// The layout implements the nav
if (drawer != null){
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
}
// Other Nav code ommitted as its too verbose
}
Then the Layout is passed from the activity as folows
public class Home extends BaseActivity {
private final String TAG = "Home";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.setLayout(R.layout.activity_home);
super.onCreate(savedInstanceState);
// Other Activity code
}
}
Is there a better way to achieve this?
Maybe setting a base layout with a content frame and inflating into that?
Any suggestions would be appreciated.

You can follow BaseActivity from Google IO application. Just override setContentView and you dont need setLayout
Here is my BaseActivity
package com.vtcmobile.kqviet.activity;
public class BaseActivity extends AppCompatActivity {
private Toolbar toolbar;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private NavigationView navigationView;
protected Context mContext;
public NavigationView getNavigationView() {
return navigationView;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = BaseActivity.this;
}
#Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
initToolbar();
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
private void setUpNav() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(BaseActivity.this, drawerLayout, R.string.app_name, R.string.app_name);
drawerLayout.setDrawerListener(drawerToggle);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
navigationView = (NavigationView) findViewById(R.id.navigation);
// Setting Navigation View Item Selected Listener to handle the item
// click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
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
Intent intent;
switch (menuItem.getItemId()) {
case R.id.xxxx:
return true;
}
return false;
}
});
// Setting the actionbarToggle to drawer layout
// calling sync state is necessay or else your hamburger icon wont show
// up
drawerToggle.syncState();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setUpNav();
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.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) {
if (drawerToggle.onOptionsItemSelected(item))
return true;
// 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

I make some changes in BaseActivity class using inflating layout of baseactivity and reuse, you can use following class for extend only into any one of your activity class.
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class BaseActivity extends AppCompatActivity {
public Toolbar toolbar;
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle drawerToggle;
public NavigationView navigationView;
public Context mContext;
public NavigationView getNavigationView() {
return navigationView;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = BaseActivity.this;
setContentView(R.layout.base_activity);
}
#Override
public void setContentView(int layoutResID) {
DrawerLayout fullView = (DrawerLayout)getLayoutInflater().inflate(R.layout.base_activity, null);
FrameLayout activityContainer = (FrameLayout) fullView.findViewById(R.id.activity_content);
getLayoutInflater().inflate(layoutResID, activityContainer, true);
super.setContentView(fullView);
initToolbar();
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
private void setUpNav() {
drawerLayout = (DrawerLayout) findViewById(R.id.activity_container);
drawerToggle = new ActionBarDrawerToggle(BaseActivity.this, drawerLayout, R.string.app_name, R.string.app_name);
drawerLayout.setDrawerListener(drawerToggle);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
navigationView = (NavigationView) findViewById(R.id.navigation);
// Setting Navigation View Item Selected Listener to handle the item
// click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
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
Intent intent;
switch (menuItem.getItemId()) {
case R.id.xxxx:
return true;
}
return false;
}
});
// Setting the actionbarToggle to drawer layout
// calling sync state is necessay or else your hamburger icon wont show
// up
drawerToggle.syncState();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setUpNav();
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.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) {
if (drawerToggle.onOptionsItemSelected(item))
return true;
// 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my base_activity.xml,
<android.support.v4.widget.DrawerLayout
android:id="#+id/activity_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
/>
<FrameLayout
android:id="#+id/activity_content"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
/>
</android.support.v4.widget.DrawerLayout>

You can refer to my following code, pay attention to addContentView in my base activity (here I name it NavigationDrawerActivity)
Base activity:
public class NavigationDrawerActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(toggle);
toggle.syncState();
}
/**
* called in extending activities instead of setContentView...
*
* #param layoutId The content Layout Id of extending activities
*/
public void addContentView(int layoutId) {
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(layoutId, null, false);
mDrawerLayout.addView(contentView, 0);
}
}
Then in other activities, for example, MainActivity:
public class MainActivity extends NavigationDrawerActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.addContentView(R.layout.activity_main);
}
}
Hope this helps!

you could either override setContentView in your BaseActivity and initialised everything after the super call or move all the DrawerLayout related stuff to a protected method and call it from each children of BaseActivity, after you call setContentView. I think the first should be straightforward an, from what you posted, you can avoid to override onCreate in the BaseActivity

Common Navigation DraweFor All Activity
## BaseActivity.java ##
public class BaseActivity extends FragmentActivity
{
final String[] navDrawMenuItems = {"My Project" , "My Project1", "MyProject2", "MyProject3" ,"MyProject4","MyProject5","MyProject6"};
final int[] navDrawMenuIcons = {R.drawable.vendor,
R.drawable.vendor,
R.drawable.vendor,
R.drawable.vendor,
R.drawable.log_icon,
R.drawable.vendor,
};
public RelativeLayout mRelativeLayout;
public FrameLayout actContent;
public ListView navList;
LinearLayout drawer_List;
TextView text_emp_name;
public MenuDrawerAdapter menuDrawerAdapter;
public ArrayList<Vendor_Wrapper> menuDrawerList = new ArrayList<>();
public DrawerArrowDrawable drawerArrowDrawable;
public ImageView drawer_indicator;
public DrawerLayout drawer_layout;
public float offset;
public boolean flipped;
SharedPreferences _SP;
SharedPreferences.Editor _EDITOR;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
for (int i = 0; i < navDrawMenuItems.length; i++)
{
menuDrawerList.add(new Vendor_Wrapper(""+i,navDrawMenuItems[i], navDrawMenuIcons[0]));
}
}
#Override
public void setContentView(int layoutResID)
{
mRelativeLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_base, null);
actContent = (FrameLayout) mRelativeLayout.findViewById(R.id.main);
// set the drawer dialog_view as main content view of Activity.
setContentView(mRelativeLayout);
// add dialog_view of BaseActivities inside framelayout.i.e. frame_container
getLayoutInflater().inflate(layoutResID, actContent, true);
drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
// =========================================
final Resources resources = getResources();
drawerArrowDrawable = new DrawerArrowDrawable(resources);
drawer_indicator = (ImageView) findViewById(R.id.drawer_indicator);
drawerArrowDrawable.setStrokeColor(resources.getColor(android.R.color.white));
drawer_indicator.setImageDrawable(drawerArrowDrawable);
// =========================================
text_emp_name=(TextView)findViewById(R.id.text_emp_name) ;
_SP = getSharedPreferences(Constants.pref_name, MODE_PRIVATE);
text_emp_name.setText(_SP.getString("empName",""));
drawer_List=(LinearLayout)findViewById(R.id.drawer_List);
navList = (ListView) findViewById(R.id.drawer_List1);
menuDrawerAdapter = new MenuDrawerAdapter(BaseActivity.this, menuDrawerList);
navList.setAdapter(menuDrawerAdapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent intent;
// Toast.makeText(getApplicationContext(),"position "+position,30).show();
Log.i(Constants.TAG,"drawer_position: "+position);
switch (position)
{
case 0:
intent = new Intent(BaseActivity.this, List_of_projects.class);
startActivityForResult(intent,Constants.EXIT);
//
break;
case 1:
intent = new Intent(BaseActivity.this, List_of_projects.class);
startActivityForResult(intent,Constants.EXIT);
// drawer_indicator.performClick();
break;
case 2:
intent = new Intent(BaseActivity.this, List_of_projects.class);
startActivityForResult(intent,Constants.EXIT);
// drawer_indicator.performClick();
break;
case 3:
intent = new Intent(BaseActivity.this, List_of_projects.class);
startActivityForResult(intent,Constants.EXIT);
// drawer_indicator.performClick();
break;
case 4:
intent = new Intent(BaseActivity.this, List_of_projects.class);
intent.putExtra("Type","Complaints");
startActivityForResult(intent,Constants.EXIT);
// drawer_indicator.performClick();
break;
case 5:
intent = new Intent(BaseActivity.this, List_of_projects.class);
intent.putExtra("Type","Suggestions");
startActivityForResult(intent,Constants.EXIT);
break;
case 6:
intent = new Intent(BaseActivity.this, List_of_projects.class);
startActivityForResult(intent,Constants.EXIT);
break;
case 7:
System.out.println("Logout clickedddddd ");
SharedPreferences.Editor editor = getSharedPreferences("my_pref", MODE_PRIVATE).edit();
editor.clear();
editor.commit();
setResult(Constants.EXIT);
finish();
break;
default:
break;
}
}
});
initViewsandSharedPreferencesandSQLiteAdapter();
clickToViews();
}
public void setMenuDrawer(ArrayList<Vendor_Wrapper> menuDrawerList, String email)
{
navList = (ListView) findViewById(R.id.drawer_List1);
menuDrawerAdapter = new MenuDrawerAdapter(BaseActivity.this, menuDrawerList);
navList.setAdapter(menuDrawerAdapter);
}
public void initViewsandSharedPreferencesandSQLiteAdapter()
{
_SP = getSharedPreferences(Constants.TAG, MODE_PRIVATE);
_EDITOR = _SP.edit();
drawer_indicator_LL = (LinearLayout) findViewById(R.id.drawer_indicator_LL);
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
#Override
public void onBackPressed()
{
super.onBackPressed();
if (drawer_layout.isDrawerVisible(Gravity.RIGHT))
{
drawer_layout.closeDrawer(drawer_List);
}
else
{
finish();
}
}
public void clickToViews()
{
drawer_layout.setDrawerListener(new DrawerLayout.SimpleDrawerListener()
{
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
offset = slideOffset;
// Sometimes slideOffset ends up so close to but not quite 1 or 0.
if (slideOffset >= .995)
{
flipped = true;
drawerArrowDrawable.setFlip(flipped);
} else if (slideOffset <= .005)
{
flipped = false;
drawerArrowDrawable.setFlip(flipped);
}
drawerArrowDrawable.setParameter(offset);
}
});
drawer_indicator.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (drawer_layout.isDrawerVisible(Gravity.RIGHT))
{
drawer_layout.closeDrawer(drawer_List);
}
else
{
drawer_layout.openDrawer(drawer_List);
}
}
});
drawer_indicator_LL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer_layout.isDrawerVisible(Gravity.RIGHT)) {
drawer_layout.closeDrawer(drawer_List);
} else {
drawer_layout.openDrawer(drawer_List);
}
}
});
}
public void NavigationPerformClick()
{
drawer_indicator.performClick();
}
private class MenuDrawerAdapter extends BaseAdapter
{
ArrayList<Vendor_Wrapper> menuDrawerList;
Context context;
public MenuDrawerAdapter(Context context, ArrayList<Vendor_Wrapper> menuDrawerList)
{
super();
this.context = context;
this.menuDrawerList = menuDrawerList;
}
#Override
public int getCount()
{
return menuDrawerList.size();
}
#Override
public Object getItem(int position)
{
return position;
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater layoutInflater = LayoutInflater.from(BaseActivity.this);
ViewHolder viewHolder;
if (convertView == null)
{
viewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.row_menu_drawer, null);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
viewHolder.imgIcon = (ImageView) convertView.findViewById(R.id.img_icon);
viewHolder.main_RL = (RelativeLayout)convertView.findViewById(R.id.main_RL);
viewHolder.imgIcon.setVisibility(View.GONE);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
Vendor_Wrapper menuDrawerModel = menuDrawerList.get(position);
//## Setup Data below
String Name = menuDrawerModel.getName();
String id = menuDrawerModel.getId();
viewHolder.tvTitle.setText(menuDrawerModel.getName());
// viewHolder.main_RL.setOnClickListener(new ClickToView(BaseActivity.this,position,id,Name));
viewHolder.imgIcon.setImageResource(menuDrawerModel.getDrawable_icon());
return convertView;
}
public class ViewHolder
{
TextView tvTitle;
ImageView imgIcon;
RelativeLayout main_RL;
}
}
protected class MenuDrawerModel
{
private String title;
private int icon;
public String Icon_url;
public MenuDrawerModel(String title, int icon, String icon_url) {
this.title = title;
this.icon = icon;
Icon_url = icon_url;
}
public MenuDrawerModel(String title, int icon)
{
super();
this.title = title;
this.icon = icon;
}
public MenuDrawerModel() {
super();
}
public String getTitle() {
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon)
{
this.icon = icon;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("Logout onActivityResult "+resultCode);
if(resultCode==Constants.EXIT)
{
setResult(Constants.EXIT);
finish();
}
}
}
## MainActivity.java ##
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
## activity_base.xml ##
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/header_view"
layout="#layout/layout_header_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/header_view">
</FrameLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/drawer_List"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_marginTop="50dp"
android:background="#color/white"
android:choiceMode="singleChoice"
android:orientation="vertical"
android:weightSum="10">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:background="#drawable/bagroundg"
android:orientation="vertical"
android:visibility="gone"
android:weightSum="5">
</LinearLayout>
<ListView
android:id="#+id/drawer_List1"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/white"
android:choiceMode="singleChoice" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
## activity_main.xml ##
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Hello World!"
android:textSize="30dp" />
</LinearLayout>
</RelativeLayout>
public class Vendor_Wrapper
{
private String id;
public Vendor_Wrapper(String id, String name, int drawable_icon)
{
this.id = id;
Name = name;
this.drawable_icon = drawable_icon;
}
private String Name;
private String contact_no;
private String Email_id;
private String Address;
private String img;
private String PAY_MODE;
private String min;
private String max;
private String imgs;
private int drawable_icon;
public int getDrawable_icon() {
return drawable_icon;
}
public void setDrawable_icon(int drawable_icon) {
this.drawable_icon = drawable_icon;
}
public String getEmail_id() {
return Email_id;
}
public void setEmail_id(String email_id) {
Email_id = email_id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getContact_no() {
return contact_no;
}
public void setContact_no(String contact_no) {
this.contact_no = contact_no;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getPAY_MODE() {
return PAY_MODE;
}
public void setPAY_MODE(String PAY_MODE) {
this.PAY_MODE = PAY_MODE;
}
public String getMin() {
return min;
}
public void setMin(String min) {
this.min = min;
}
public String getMax() {
return max;
}
public void setMax(String max) {
this.max = max;
}
public String getImgs() {
return imgs;
}
public void setImgs(String imgs) {
this.imgs = imgs;
}
public Vendor_Wrapper(String id, String name, String contact_no, String email_id, String address, String img, String PAY_MODE, String min, String max, String imgs) {
this.id = id;
Name = name;
this.contact_no = contact_no;
Email_id = email_id;
Address = address;
this.img = img;
this.PAY_MODE = PAY_MODE;
this.min = min;
this.max = max;
this.imgs = imgs;
}
}

Here is my example of implementing to BaseActivity, I found I did it differently and it worked for me.
My Base Activity
public abstract class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
//swap this to a switch statement
if (id == R.id.nav_newgame) {
// Start new game
Log.e("Base","new Game");
} else if (id == R.id.nav_players) {
} else if (id == R.id.nav_history) {
} else if (id == R.id.nav_tools) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_about) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Any activity sharing the same Navigation Drawer
public class MainActivity extends BaseActivity
{
NavigationView navigationView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
Allowing one dynamic Nav Drawer in your base activity saving you the trouble of writing code over and over. Additionally you can override the Base Activity's Nav Drawer and make different results for different situations.

Related

Recycler view not displaying

I just converted MyConsumptionList activity to a fragment.In the activity, the recycler view was displaying perfectly but in the fragment, it is not displaying. while compiling there is no error and the app is running properly.
I want to display Consumption List as an item in navigation bar. Please help me out.
code for MyConsumptionList.java
public class MyConsumptionList extends Fragment{
DatabaseReference db;
FirebaseHelper helper;
RecyclerViewAdapter adapter;
RecyclerView rv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_my_consumption_list,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Consumption List");
startList();
}
#Override
public void onStart() {
super.onStart();
startList();
}
#Override
public void onResume() {
super.onResume();
startList();
}
public void startList(){
//initialize rv
rv=(RecyclerView)getView().findViewById(R.id.recyclerView);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
//initialize fb
db= FirebaseDatabase.getInstance().getReference().child("My consumption");
helper=new FirebaseHelper(db);
//adapter
adapter=new RecyclerViewAdapter(getActivity(),helper.retrieve());
rv.setAdapter(adapter);
}
code for recycler view adapter.
public class RecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> {
static String key_UID=null;
protected Context c;
private ArrayList<SaveData>sd;
FirebaseDatabase fb;
public RecyclerViewAdapter(Context c, ArrayList<SaveData> sd) {
this.c = c;
this.sd = sd;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(c).inflate(R.layout.recycler_view_row,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.ItemnameTxt.setText(sd.get(position).getName());
holder.BrandNameTxt.setText(sd.get(position).getBrand_Name());
holder.CaloriesTxt.setText("Calories: " + sd.get(position).getSave_calories());
holder.FatTxt.setText("Fat: " + sd.get(position).getSave_fat());
holder.Servingtxt.setText(sd.get(position).getServing_Size());
//db = FirebaseDatabase.getInstance().getReference();
//key_UID=sd.get(position).getName();
// holder.deleteButton.setOnClickListener(new View.OnClickListener() {
// #Override
//public void onClick(View v) {
//});
}
#Override
public int getItemCount() {
return this.sd.size();
}
code for Firebase Helper.java
public class FirebaseHelper {
DatabaseReference db;
ArrayList<SaveData> sd=new ArrayList<>();
//pass database reference
public FirebaseHelper(DatabaseReference db){
this.db=db;
}
//read by hooking onto database operation callbacks
public ArrayList<SaveData>retrieve(){
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
SaveData saves=dataSnapshot.getValue(SaveData.class);
sd.add(saves);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
SaveData saves=dataSnapshot.getValue(SaveData.class);
sd.add(saves);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return sd;
}
my content_navigationBar.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="nutritionapp.listview.bio.ayushsharma.nutritionapp.
Navigationbar"
tools:showIn="#layout/app_bar_navigationbar">
</RelativeLayout>
my navigationBar.java
public class Navigationbar extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigationbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main, new MainActivity());
ft.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigationbar, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment frag=null;
if (id == R.id.nav_home) {
// Handle the input action
frag=new MainActivity();
} else if (id == R.id.nav_consuptionList) {
frag=new MyConsumptionList();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
if(frag != null){
FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main,frag);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
consumptionList.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="nutritionapp.listview.bio.ayushsharma.nutritionapp.
MyConsumptionList">
<TextView
android:id="#+id/consTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Consumption List"
android:layout_centerHorizontal="true"
android:textSize="15sp"
android:textStyle="bold"
android:textColor="#dc0d28"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerView"
android:layout_below="#+id/consTitle"
android:layout_marginTop="10dp"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
where is your class ViewHolder in adapter.
where you initialize your
holder.ItemnameTxt
holder.BrandNameTxt
holder.CaloriesTxt
I think your problem is when you do
new RecyclerViewAdapter(getActivity(),helper.retrieve());
your array is empty since they data is only added when something else raise the event of ChildEventListener event.
Thus you should notify your adapter by calling notifyDataSetChanged() after adding the data to your array.

Navigation drawer stuck when offline data loading

I am developing news app user can download video and image.
So I developed navigation drawer with different fragment with material design. But I am facing some problem in it when I click gallery (where I show the downloaded video and images) it stuck for some time and then open fragment. it happened only in specific fragment but not all.
see Video here.
Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
TextView mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null)
{
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
mTitle = (TextView) mToolbar.findViewById(R.id.tv_toolbar_title);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
/* if (id == R.id.action_search) {
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}*/
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
mTitle.setText(title);
break;
case 1:
fragment = new GalleryFragment();
title = getString(R.string.title_gallery);
mTitle.setText(title);
break;
case 2:
fragment = new SettingFragment();
title = getString(R.string.title_setting);
mTitle.setText(title);
break;
case 3:
fragment = new AboutusFragment();
title = getString(R.string.title_aboutus);
mTitle.setText(title);
break;
case 4:
fragment = new ContactusFragment();
title = getString(R.string.title_contactus);
mTitle.setText(title);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
if (getSupportActionBar() != null)
getSupportActionBar().setTitle(title);
}
}
}
FragmentDrawer.java
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private static DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private static int[] ic_nav_drw = {R.drawable.ic_setting, R.drawable.gallery, R.drawable.setting, R.drawable.aboutus, R.drawable.contactus};
private FragmentDrawerListener drawerListener;
ImageView profile;
TextView tv_name;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
navItem.setIcon(ic_nav_drw[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
tv_name = (TextView) layout.findViewById(R.id.tv_name);
profile = (ImageView) layout.findViewById(R.id.profile);
SharedPreferences settings = getActivity().getSharedPreferences("preference", 0);
String name = settings.getString("name","");
tv_name.setText(name);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "You click profile", Toast.LENGTH_SHORT).show();
}
});
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);
}
}
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">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.bicubic.botadnews.fragment.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
fragment_navigation_drawer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/nav_header_container"
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary">
<ImageView
android:id="#+id/profile"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerInParent="true"
android:scaleType="fitCenter"
android:src="#drawable/ic_profile" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textColor="#color/white"
android:textSize="20sp"
android:layout_marginBottom="10dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/nav_header_container"
android:layout_marginTop="15dp" />
</RelativeLayout>
Here is my gallery fragment
Editted GalleryFragment.java
public class GalleryFragment extends Fragment implements View.OnClickListener {
View rootView;
static RecyclerView rv_video;
RecyclerView rv_image;
static List<File> videofiles;
static List<File> imagefiles;
Button bt_video, bt_image;
private static Context context ;
public GalleryFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
rv_video = (RecyclerView) rootView.findViewById(R.id.rv_video);
rv_image = (RecyclerView) rootView.findViewById(R.id.rv_image);
bt_video = (Button) rootView.findViewById(R.id.bt_video);
bt_image = (Button) rootView.findViewById(R.id.bt_image);
bt_video.setBackgroundResource(R.color.colorAccent);
bt_video.setOnClickListener(this);
bt_image.setOnClickListener(this);
context = getActivity();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
rv_video.setLayoutManager(linearLayoutManager);
rv_video.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getActivity());
rv_image.setLayoutManager(linearLayoutManager1);
rv_image.setHasFixedSize(true);
videofiles = new ArrayList<>();
imagefiles = new ArrayList<>();
new LoadOfflineData().execute();
rootView.post(new Runnable() {
#Override
public void run() {
new LoadOfflineData().execute();
}
});
// Inflate the layout for this fragment
return rootView;
}
public static class LoadOfflineData extends AsyncTask<Void, Void, Void> {
ProgressDialog progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(context);
progressBar.setMessage("Loading...");
progressBar.show();
}
#Override
protected Void doInBackground(Void... voids) {
String video_path = Environment.getExternalStorageDirectory().getPath() + "/Botad News/Videos";
Log.d("Files", "Path: " + video_path);
File checkFile = new File(video_path);
// videofiles = new ArrayList<>();
File[] files = new File[0];
if (checkFile.isDirectory()) {
File directory = new File(video_path);
files = directory.listFiles();
videofiles.addAll(Arrays.asList(files));
} else {
// Toast.makeText(getActivity(), "Folder not Found", Toast.LENGTH_SHORT).show();
Log.e(TAG, "doInBackground: folder not found" );
}
String image_path = Environment.getExternalStorageDirectory().getPath() + "/Botad News/Images";
Log.d("Files", "Path: " + image_path);
File checkFileImages = new File(image_path);
// imagefiles = new ArrayList<>();
File[] filesImage = new File[0];
if (checkFileImages.isDirectory()) {
File directory = new File(image_path);
filesImage = directory.listFiles();
imagefiles.addAll(Arrays.asList(filesImage));
} else {
// Toast.makeText(getActivity(), "Folder not Found", Toast.LENGTH_SHORT).show();
Log.e(TAG, "doInBackground: folder not found" );
}
Log.d("Files", "Size: " + files.length);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressBar.dismiss();
if (videofiles.size() > 0) {
RvGalleryVideoAdapter adapter = new RvGalleryVideoAdapter(videofiles, context);
rv_video.setAdapter(adapter);
} else {
Toast.makeText(context, "Data not found", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bt_video:
bt_video.setBackgroundResource(R.color.colorAccent);
bt_image.setBackgroundResource(R.color.colorPrimary);
rv_image.setVisibility(View.GONE);
rv_video.setVisibility(View.VISIBLE);
if (videofiles.size() > 0) {
RvGalleryVideoAdapter adapter = new RvGalleryVideoAdapter(videofiles, getActivity());
rv_video.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "Data not found", Toast.LENGTH_SHORT).show();
}
break;
case R.id.bt_image:
bt_image.setBackgroundResource(R.color.colorAccent);
bt_video.setBackgroundResource(R.color.colorPrimary);
rv_image.setVisibility(View.VISIBLE);
rv_video.setVisibility(View.GONE);
if (imagefiles.size() > 0) {
RvGalleryImageAdapter adapter_image = new RvGalleryImageAdapter(imagefiles, getActivity());
rv_image.setAdapter(adapter_image);
} else {
Toast.makeText(getActivity(), "Data not found", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
}
In your AsyncTask, you are accessing the class fields of the Fragment! This will actually block the UI Thread :-(
The lines
videofiles = new ArrayList<>();
imagefiles = new ArrayList<>();
cannot be there. You need to create local lists, put data in them and then return it in onPostExecute().
Start by replacing
public class LoadOfflineData extends AsyncTask<Void, Void, Void> {
with
public static class LoadOfflineData extends AsyncTask<Void, Void, Void> {
This will give you errors in places you need to change :-)
I found the answer.
It is in my RecyclerAdapter when i get thumbnail using inbuilt class so it will take time to set it see my
Old code
Bitmap bmThumbnail;
//MICRO_KIND, size: 96 x 96 thumbnail
bmThumbnail = ThumbnailUtils.createVideoThumbnail(sdcard_path + "/Botad News/Videos/" + fileName, MediaStore.Images.Thumbnails.MICRO_KIND);
holder.img_main.setImageBitmap(bmThumbnail);
New code is using glide library so lib automatically handle the thread i assume.
BitmapPool bitmapPool = Glide.get(context).getBitmapPool();
int microSecond = 6000000;// 6th second as an example
VideoBitmapDecoder videoBitmapDecoder = new VideoBitmapDecoder(microSecond);
FileDescriptorBitmapDecoder fileDescriptorBitmapDecoder = new FileDescriptorBitmapDecoder(videoBitmapDecoder, bitmapPool, DecodeFormat.PREFER_ARGB_8888);
Glide.with(context)
.load(sdcard_path + "/Botad News/Videos/" + fileName)
.asBitmap()
.override(250,250)// Example
.videoDecoder(fileDescriptorBitmapDecoder)
.into(holder.img_main);
Found solution HERE....

Update an TextView in NavigationDrawer after input from user in previous activity

There is some information that I want to display in the NavigationDrawer. This information is entered by the user in a previous activity. I use an intent to send the information to the Main Activity for the Drawer.
MainActivity (After user entered details)
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
String info = intent.getStringExtra("info");
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.nav_item_dashboard);
break;
......
}
I have a specific layout for the navigation drawer and it contains a textview which I want to update with the String test. This is the fragment code and the xml for it.
FragmentDrawer Class
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
navItem.setIcon(icons.getResourceId(i,-1));
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 = getResources().obtainTypedArray(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);
TextView userID = (TextView) layout.findViewById(R.id.nav_title_user);
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();
}
});
}
FramgentDrawer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/nav_header_container"
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary">
......
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceInverse"
android:text="#string/welcome_user"
android:id="#+id/nav_title_user"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"/>
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_below="#id/nav_header_container" />
I have managed to update the list in the drawer with Icons, Labels and a Header. I have done so by using a RecyclerViewAdapter.
The problem that I am having is that these details were from the resources (strings.xml).
How can I update a textview on a NavigationFragment when it has been created? How can I send a value to the fragment so that it will be used during OnCreateView of the fragment?
I was looking too much into it. The solution was quite simple...Even though it took me 3 hrs to figure this out :/
In the NavigationFragment, I created a method to update a textview with a string. In the MainActivity where I get the information from the intent, I just called the method like this:
drawerFragment.setUserTextView(info);
This is why taking breaks are important... ^^

How to Create Multi-Level menus in navigation drawer layout

I want to create Multi-Level Menus in drawer Layout. My Activity.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">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.android.ShoppingMazza.activity.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
Here My fragment_navigation_drawer.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp" />
Here My 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 FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
Here My MainActivity.java:-
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
My Current View of App below:-
but i want multi-level submenus (more than 3) in Home menu.
I am new in android developing help me. Thanks in advance
You can simply use Android TreeView Library.
Reference: https://github.com/bmelnychuk/AndroidTreeView
And if you just need three levels, you can create a threelevel custom expandable listview.
Reference: https://github.com/talhahasanzia/Three-Level-Expandable-Listview
You can use ExpandableListView instead of RecyclerView. Here is a nice tutorial to implement it.
Expandable ListView
And if you really want to use RecyclerView you can look at the following library:
Expandable RecyclerView

Navigation Drawer does not open when I click App name from ActionBar

I have implemented the Navigation Drawer into my new app. But I cannot get the App name from ActionBar to toggle the Navigation Drawer. However, when I drag the navigation drawer, the ActionBar respond to this action by changing to an arrow.
Here is my code:
services_activity_main.xml
<LinearLayout
android:orientation="vertical"
android:id="#+id/container_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/title_bar_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
<LinearLayout
android:id="#+id/contents_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp">
</LinearLayout>
<LinearLayout
android:id="#+id/navigation_bar_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
<FrameLayout
android:id="#+id/services_navigation_drawer_layout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start">
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
services_fragment_navigation_drawer.xml
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/services_navigation_drawer_gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:choiceMode="multipleChoice"
android:focusable="true"
android:focusableInTouchMode="true"
android:background="#EEE" />
MainActivity.java
public class MainActivity
extends Activity
implements BaseControllerFragment.ControllerCallbacks,
ServicesNavigationDrawerFragment.NavigationDrawerCallbacks {
public final static String TAG = "MainActivity";
LinearLayout titleBarLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.services_activity_main);
titleBarLayout = (LinearLayout) findViewById(R.id.title_bar_layout);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.services_navigation_drawer_layout,
new ServicesNavigationDrawerFragment(),
TAG + "." + ServicesNavigationDrawerFragment.TAG).commit();
}
#Override
public void updateTitleBar(View view) {
titleBarLayout.removeAllViews();
titleBarLayout.addView(view);
titleBarLayout.invalidate();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
replaceContainerContents(new BuildLicenseControllerFragment());
return;
case 1:
replaceContainerContents(new BuildLicenseControllerFragment());
return;
}
}
private void replaceContainerContents(BaseControllerFragment controllerFragment) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contents_layout,
controllerFragment,
TAG + "." + controllerFragment.TAG).commit();
}
}
ServicesNavigationDrawerFragment.java
public class ServicesNavigationDrawerFragment extends Fragment {
public final static String TAG = "ServicesNavigationDrawerFragment";
String[] titles = {
"String 1", // 0
"String 2" // 1
};
int[] images = {
R.drawable.service_build_license,
R.drawable.service_build_license
};
private final static String STATE_SELECTED_POSITION = "SELECTED_POSITION";
private final static String PREF_USER_LEARNED_DRAWER = "USER_LEARNED_DRAWER";
private int selectedPosition = 0;
private boolean fromSavedInstance;
private boolean userLearnedDrawer;
GridView drawerGridView;
DrawerLayout drawerLayout;
FrameLayout navigationDrawerLayout;
ActionBarDrawerToggle drawerToggle;
private NavigationDrawerCallbacks callbacks;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
userLearnedDrawer = sharedPreferences.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if(savedInstanceState != null) {
selectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
fromSavedInstance = true;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
drawerGridView = (GridView) inflater.inflate(R.layout.services_fragment_navigation_drawer, container, false);
drawerGridView.setAdapter(new ServicesAdapter(titles, images));
drawerGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
return drawerGridView;
}
#Override
public void onAttach(final Activity activity) {
super.onAttach(activity);
try {
callbacks = (NavigationDrawerCallbacks) activity;
drawerLayout = (DrawerLayout) activity.findViewById(R.id.activity_services_drawer_layout);
navigationDrawerLayout = (FrameLayout) activity.findViewById(R.id.services_navigation_drawer_layout);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, R.string.app_name, R.string.app_name) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.i(TAG, "Drawer Closed!");
if (!isAdded()) {
return;
}
// activity.invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Log.i(TAG, "Drawer Opened!");
if (!isAdded()) {
return;
}
if( ! userLearnedDrawer) {
userLearnedDrawer = true;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
sharedPreferences.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
// activity.invalidateOptionsMenu();
}
};
if( ! userLearnedDrawer && ! fromSavedInstance) {
drawerLayout.openDrawer(navigationDrawerLayout);
}
drawerLayout.post(new Runnable() {
#Override
public void run() {
drawerToggle.syncState();
}
});
drawerLayout.setDrawerListener(drawerToggle);
} catch(ClassCastException e) {
throw new ClassCastException(activity.getClass() + " must implements NavigationDrawerCallbacks interface.");
}
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, selectedPosition);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(int position) {
selectedPosition = position;
if(drawerGridView != null) {
drawerGridView.setItemChecked(position, true);
}
if(drawerLayout != null) {
drawerLayout.closeDrawer(navigationDrawerLayout);
}
if(callbacks != null) {
callbacks.onNavigationDrawerItemSelected(position);
}
}
private class ServicesAdapter extends BaseAdapter {
public final static String TAG = "ServicesAdapter";
private Context context;
private LayoutInflater inflater;
private String[] titles;
private int[] images;
private ServicesAdapter(String[] titles, int[] images) {
if(titles.length != images.length) {
throw new RuntimeException("You Must Provide Same Number of Titles and Images.");
}
context = getActivity();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.titles = titles;
this.images = images;
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object getItem(int position) {
return titles[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = null;
if(convertView != null) {
textView = (TextView) convertView;
} else {
textView = (TextView) inflater.inflate(R.layout.services_layout_drawer_item, parent, false);
}
Log.i(TAG, textView.getCompoundDrawables()[1].getBounds().toString());
Drawable drawable = context.getResources().getDrawable(images[position]);
drawable.setBounds(new Rect(0, 0, 128, 128));
textView.setText(titles[position]);
textView.setCompoundDrawables(null, drawable, null, null);
return textView;
}
}
public interface NavigationDrawerCallbacks {
public void onNavigationDrawerItemSelected(int position);
}
}
You shouldn't handle your navigation drawer from fragment.
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, R.string.app_name, R.string.app_name) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.i(TAG, "Drawer Closed!");
if (!isAdded()) {
return;
}
// activity.invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Log.i(TAG, "Drawer Opened!");
if (!isAdded()) {
return;
}
if( ! userLearnedDrawer) {
userLearnedDrawer = true;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
sharedPreferences.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
// activity.invalidateOptionsMenu();
}
};
if( ! userLearnedDrawer && ! fromSavedInstance) {
drawerLayout.openDrawer(navigationDrawerLayout);
}
drawerLayout.post(new Runnable() {
#Override
public void run() {
drawerToggle.syncState();
}
});
drawerLayout.setDrawerListener(drawerToggle);
} catch(ClassCastException e) {
throw new ClassCastException(activity.getClass() + " must implements NavigationDrawerCallbacks interface.");
}
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, selectedPosition);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}a
Shift above code from fragment to your MAinActivity.java
Make sure you have everything on your drawerToggle like follows
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};

Categories

Resources