My application crashes when I flip orientation. If the commented out line in onCreate runs I can't flip orientation at all. without it I can flip but can't change my background image but when it flips back it still crashes.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private DrawerLayout mDrawerLayout;
private ListView mListView;
private ImageView bgimage;
int[] drwables = {R.drawable.cindy, R.drawable.fred, R.drawable.kate, R.drawable.keith, R.drawable.matt, R.drawable.rickey};
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
Toast.makeText(this, "made it", Toast.LENGTH_SHORT).show();
int n = savedInstanceState.getInt("imageId");
Toast.makeText(this, ""+n, Toast.LENGTH_SHORT).show();
bgimage = (ImageView) findViewById(R.id.imgOne);
int[] drwables = {R.drawable.cindy, R.drawable.fred, R.drawable.kate, R.drawable.keith, R.drawable.matt, R.drawable.rickey};
Toast.makeText(this, ""+drwables.length, Toast.LENGTH_SHORT).show();
//This code here
//bgimage.setImageResource(drwables[n]);
}
else{
bgimage = (ImageView) findViewById(R.id.imgOne);
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mListView = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
String[] names = getResources().getStringArray(R.array.bandImages);
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, R.layout.nav_list_row, R.id.textView, names);
mListView.setAdapter(itemsAdapter);
mListView.setOnItemClickListener(this);
toggle = new ActionBarDrawerToggle(this, mDrawerLayout, (Toolbar) findViewById(R.id.toolbar), R.string.open, R.string.closed) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(getTitle());
invalidateOptionsMenu();
}
public void onDrawerOpened(View view) {
super.onDrawerOpened(view);
getSupportActionBar().setTitle(getTitle());
invalidateOptionsMenu();
}
};
mDrawerLayout.addDrawerListener(toggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.syncState();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
int n = Integer.parseInt(bgimage.getTag().toString());
savedInstanceState.putInt("imageId", n);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mListView);
menu.findItem(R.id.action_about).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#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 void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bgimage = (ImageView) findViewById(R.id.imgOne);
bgimage.setImageResource(drwables[position]);
bgimage.setTag(position);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(R.id.action_about == id){
Toast.makeText(this, "Lab 2 Spring 2016, Zack G Johnson", Toast.LENGTH_SHORT).show();
return true;
}
else{
return super.onOptionsItemSelected(item);
}
}
}
Try to place setContentView method before finding and using layout elements.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//put it here
setContentView(R.layout.activity_main);
if(savedInstanceState != null){
Toast.makeText(this, "made it", Toast.LENGTH_SHORT).show();
int n = savedInstanceState.getInt("imageId");
Toast.makeText(this, ""+n, Toast.LENGTH_SHORT).show();
bgimage = (ImageView) findViewById(R.id.imgOne);
int[] drwables = {R.drawable.cindy, R.drawable.fred, R.drawable.kate, R.drawable.keith, R.drawable.matt, R.drawable.rickey};
Toast.makeText(this, ""+drwables.length, Toast.LENGTH_SHORT).show();
//This code here
//bgimage.setImageResource(drwables[n]);
}
else{
bgimage = (ImageView) findViewById(R.id.imgOne);
}
...
Related
I want to add slider down menu in Navigation Drawer like this.
After click left side icon, it shows like this.
What can be done for this ?
This is Navigation Drawer with ExpandableListview
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private String[] items;
private ExpandableListView mExpandableListView;
private ExpandableListAdapter mExpandableListAdapter;
private List<String> mExpandableListTitle;
private NavigationManager mNavigationManager;
private Map<String, List<String>> mExpandableListData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
mExpandableListView = (ExpandableListView) findViewById(R.id.navList);
mNavigationManager = FragmentNavigationManager.obtain(this);
initItems();
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.nav_header, null, false);
mExpandableListView.addHeaderView(listHeaderView);
mExpandableListData = ExpandableListDataSource.getData(this);
mExpandableListTitle = new ArrayList(mExpandableListData.keySet());
addDrawerItems();
setupDrawer();
if (savedInstanceState == null) {
selectFirstItemAsDefault();
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void selectFirstItemAsDefault() {
if (mNavigationManager != null) {
String firstActionMovie = getResources().getStringArray(R.array.actionFilms)[0];
mNavigationManager.showFragmentAction(firstActionMovie);
getSupportActionBar().setTitle(firstActionMovie);
}
}
private void initItems() {
items = getResources().getStringArray(R.array.film_genre);
}
private void addDrawerItems() {
mExpandableListAdapter = new CustomExpandableListAdapter(this, mExpandableListTitle, mExpandableListData);
mExpandableListView.setAdapter(mExpandableListAdapter);
mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
getSupportActionBar().setTitle(mExpandableListTitle.get(groupPosition).toString());
}
});
mExpandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
getSupportActionBar().setTitle(R.string.film_genres);
}
});
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String selectedItem = ((List) (mExpandableListData.get(mExpandableListTitle.get(groupPosition))))
.get(childPosition).toString();
getSupportActionBar().setTitle(selectedItem);
if (items[0].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentAction(selectedItem);
} else if (items[1].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentComedy(selectedItem);
} else if (items[2].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentDrama(selectedItem);
} else if (items[3].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentMusical(selectedItem);
} else if (items[4].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentThriller(selectedItem);
} else {
throw new IllegalArgumentException("Not supported fragment type");
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
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(R.string.film_genres);
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) {
// 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();
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
For more see this https://github.com/msahakyan/expandable-navigation-drawer
I want to implement drawer functionality in my android application just like flipkart can anyone help how to show subcategories in the same drawer on the click of respected category
Try to use Expandable listview in drawer like this
https://github.com/msahakyan/expandable-navigation-drawer
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private ExpandableListView mExpandableListView;
private ExpandableListAdapter mExpandableListAdapter;
private List<String> mExpandableListTitle;
private Map<String, List<String>> mExpandableListData;
private TextView mSelectedItemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
mExpandableListView = (ExpandableListView) findViewById(R.id.navList);
mSelectedItemView = (TextView) findViewById(R.id.selected_item);
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.nav_header, null, false);
mExpandableListView.addHeaderView(listHeaderView);
mExpandableListData = ExpandableListDataSource.getData(this);
mExpandableListTitle = new ArrayList(mExpandableListData.keySet());
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
mExpandableListAdapter = new CustomExpandableListAdapter(this, mExpandableListTitle, mExpandableListData);
mExpandableListView.setAdapter(mExpandableListAdapter);
mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
getSupportActionBar().setTitle(mExpandableListTitle.get(groupPosition).toString());
mSelectedItemView.setText(mExpandableListTitle.get(groupPosition).toString());
}
});
mExpandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
getSupportActionBar().setTitle(R.string.film_genres);
mSelectedItemView.setText(R.string.selected_item);
}
});
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String selectedItem = ((List) (mExpandableListData.get(mExpandableListTitle.get(groupPosition))))
.get(childPosition).toString();
getSupportActionBar().setTitle(selectedItem);
mSelectedItemView.setText(mExpandableListTitle.get(groupPosition).toString() + " -> " + selectedItem);
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
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(R.string.film_genres);
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) {
// 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;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
In my Activity I have a drawer list that pops from the right but I'm not able to move the drawer toggle from the left to the right side. Please if somebody can help me solve this issue.I just want to move the toggle to the right of the action bar.
package com.parse.starter;
import com.parse.ParseUser;
public class UserDrawer extends AppCompatActivity {
//Declaring Variables
private ListView DrawerList;
private ArrayAdapter<String> Adapter;
private ActionBarDrawerToggle DrawerToggle;
private DrawerLayout DrawerLayout;
private String ActivityTitle;
final ParseUser currentUser = ParseUser.getCurrentUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_drawer);
DrawerList = (ListView) findViewById(R.id.navList);
DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Button Sample = (Button) findViewById(R.id.button);
}
//Method To Add Items To The List View
private void addDrawerItems() {
String[] DArray = {"Job List", "Notifications", "Messages", "Log Out"};
Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, DArray);
DrawerList.setAdapter(Adapter);
DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent i0 = new Intent(UserDrawer.this, Set_Info.class);
startActivity(i0);
} else if (position == 1) {
//Intent i1 = new Intent(Drawer1.this, AddPatient.class);
//startActivity(i1);
} else if (position == 2) {
//Intent i2 = new Intent(Drawer1.this, Notifications.class);
//startActivity(i2);
} else if (position == 3) {
//Intent i3 = new Intent(Drawer1.this, Message_Log.class);
//startActivity(i3);
} else if (position == 4) {
Intent i4 = new Intent(UserDrawer.this, MainActivity.class);
startActivity(i4);
Toast.makeText(getApplicationContext(), "You are Logged Out", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
private void setupDrawer() {
DrawerToggle = new ActionBarDrawerToggle(this, DrawerLayout,
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("Menu");
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(ActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
DrawerToggle.setDrawerIndicatorEnabled(true);
DrawerLayout.setDrawerListener(DrawerToggle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item != null && item.getItemId()==android.R.id.home){
if(DrawerLayout.isDrawerOpen(Gravity.RIGHT)){
//Notice the Gravity.Right
DrawerLayout.closeDrawer(Gravity.RIGHT);
}else{
DrawerLayout.openDrawer(Gravity.RIGHT);
}
}
return false;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
DrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
DrawerToggle.onConfigurationChanged(newConfig);
}
#SuppressWarnings("ResourceType")
public void SampleClick(View view) {
try {
Intent i = new Intent(UserDrawer.this,Set_Info.class);
startActivity(i);
} catch (Exception e) {
}
}
}
I followed a tutorial to set a navigation drawer and it worked in my main activity. Now I tried to move it to almost every other activity creating a BaseActivity, but after making changes, navigation drawer icon is inactive, and does nothing when pressed.
MainActivity code:
public class MainActivity extends BaseActivity {
private WebView mWebView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//Hide the semy cirle at th bottom of the action bar when the user slides to the top
mWebView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
//mainWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.stopLoading(); // may not be needed
switch (Locale.getDefault().toString()) {
case "es_ES":
view.loadUrl("file:///android_asset/www/errorPage.forMainActivity.es_ES.HTML");
break;
default:
view.loadUrl("file:///android_asset/www/errorPage.forMainActivity.en_US.HTML");
break;
}
}
#Override
public void onPageFinished(WebView view, String url) {
//sendRegistrationIdToBackend();
//getCookies();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("CommentsPopUp")) {
Intent a = new Intent(MainActivity.this, CommentsPopUpActivity.class);
startActivity(a);
} else if (url.contains("postPopUp")) {
Intent b = new Intent(MainActivity.this, PostPopUpActivity.class);
startActivity(b);
} else if (url.contains("ProfilePicPopUp")) {
Intent c = new Intent(MainActivity.this, ProfilePicPopUpActivity.class);
startActivity(c);
} else if (url.contains("PostPicPopUp")) {
Intent c = new Intent(MainActivity.this, PostPicsPopUpActivity.class);
startActivity(c);
} else if (url.contains("reloadIndex")) {
mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/");
} else if (Uri.parse(url).getHost().length() == 0) {
return false;
} else { // Otherwise, give the default behavior (open in browser)
mWebView.loadUrl(url);
}
return true;
}
});
mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/");
// Stop local links and redirects from opening in browser instead of WebView
// mWebView.setWebViewClient(new MyAppWebViewClient());
}
#Override
public void onBackPressed(){
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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
public void getCookies() {
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie("http://192.168.0.6/");
//Log.i("UdazzT", cookies);
}
}
BaseActivity code:
public class BaseActivity extends AppCompatActivity {
ListView mDrawerList;
RelativeLayout mDrawerPane;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
mNavItems.add(new NavItem(getResources().getString(R.string.myPosts), "", R.mipmap.ic_action_home));
mNavItems.add(new NavItem(getResources().getString(R.string.myFriends), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.findFriends), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.profileInfo), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.profilePic), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.notifications), "", R.mipmap.ic_action_settings));
mNavItems.add(new NavItem(getResources().getString(R.string.contact), "", R.mipmap.ic_action_settings));
mNavItems.add(new NavItem(getResources().getString(R.string.logOut), "", R.mipmap.ic_action_about));
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Populate the Navigtion Drawer with options
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
// Drawer Item click listeners
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItemFromDrawer(position);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
}
#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_base, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle
// If it returns true, then it has handled
// the nav drawer indicator touch event
if (mDrawerToggle.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed(){
if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)){ //replace this with actual function which returns if the drawer is open
mDrawerLayout.closeDrawer(Gravity.LEFT); // replace this with actual function which closes drawer
}
else{
super.onBackPressed();
}
}
/*
* Called when a particular item from the navigation drawer
* is selected.
* */
private void selectItemFromDrawer(int position) {
switch (position) {
case 0:
Intent a = new Intent(this, MyPostsActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(this, MyFriendsActivity.class);
startActivity(b);
break;
case 2:
Intent c = new Intent(this, FindFriendsActivity.class);
startActivity(c);
break;
case 3:
Intent d = new Intent(this, MyProfileInfoActivity.class);
startActivity(d);
break;
case 5:
Intent f = new Intent(this, MyNotificationsActivity.class);
startActivity(f);
break;
case 6:
Intent g = new Intent(this, ContactActivity.class);
startActivity(g);
break;
case 7:
//mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/signOut.php");
break;
}
mDrawerList.setItemChecked(position, true);
//setTitle(mNavItems.get(position).mTitle);
// Close the drawer
mDrawerLayout.closeDrawer(mDrawerPane);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
}
class NavItem {
String mTitle;
String mSubtitle;
int mIcon;
public NavItem(String title, String subtitle, int icon) {
mTitle = title;
mSubtitle = subtitle;
mIcon = icon;
}
}
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
#Override
public int getCount() {
return mNavItems.size();
}
#Override
public Object getItem(int position) {
return mNavItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, null);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
TextView subtitleView = (TextView) view.findViewById(R.id.subTitle);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText(mNavItems.get(position).mTitle);
subtitleView.setText(mNavItems.get(position).mSubtitle);
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
}
}
i have given this answer.
refer to this https://stackoverflow.com/a/30490289/3498931 and
in your case, implement syncState() method after the setting the listener to mDrawerLayout.
mDrawerLayout.setDrawerListener(drawerToggle);
after this statement, use the code i given in link. also you have duplication of code, remove the code from class which is not applicable. both way it is possible, but keep one only whichever works to avoid further conflict, unreadability or confustion.
I am extending my NavigationObject class to my other activity classes but the drawer would not come out when I click on the menu.
Here is my NavigationObject:
public class NavigationObject extends ActionBarActivity implements OnClickListener{
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
ListView listView;
List<RowItem> rowItems;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.navdrawer);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
System.out.println("ERROR 1");
addDrawerItems();
setupDrawer();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//junk
public void addDrawerItems() {
System.out.println("ERROR 2");
String[] drawer_Array = { "User Profile", "Setting", "Contact us", "Help", "Logout" };
String[] desc_Array = { "Private", "Change settings", "Ask us anything", "Simple Guide", "Logs out user" };
Integer[] image_Array = { R.drawable.user, R.drawable.setting, R.drawable.contactme, R.drawable.help, R.drawable.logout };
//mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, drawer_Array);
//mDrawerList.setAdapter(mAdapter);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < drawer_Array.length; i++) {
RowItem item = new RowItem(image_Array[i], drawer_Array[i], desc_Array[i]);
rowItems.add(item);
}
System.out.println("ERROR 3");
listView = (ListView) findViewById(R.id.navList);
CustomDrawerBaseAdapter adapter = new CustomDrawerBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0){
Intent toProfile = new Intent(getApplicationContext(), userprofActivity.class);
startActivity(toProfile);
//Toast.makeText(getMsgActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
else if(position == 1){
//Toast.makeText(getMsgActivity.this, "Time for an Wake!", Toast.LENGTH_SHORT).show();
}
else if(position == 2){
//Toast.makeText(getMsgActivity.this, "Time for an Eat!", Toast.LENGTH_SHORT).show();
}
else if(position == 3){
//Toast.makeText(getMsgActivity.this, "Time for an Dance!", Toast.LENGTH_SHORT).show();
}
else if(position == 4){
//Toast.makeText(getMsgActivity.this, "Time for an Sleep!", Toast.LENGTH_SHORT).show();
}
}
});
System.out.println("ERROR 4");
}
public void setupDrawer() {
//getActionBar().setDisplayHomeAsUpEnabled(true);
//getActionBar().setHomeButtonEnabled(true);
System.out.println("ERROR 5");
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
// enabling action bar app icon and behaving it as toggle button
public void onDrawerOpened(View drawerView) {
System.out.println("ERROR 5");
super.onDrawerOpened(drawerView);
listView.bringToFront();
mDrawerLayout.requestLayout();
getSupportActionBar().setTitle("User Menu Option");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerClosed(View view) {
System.out.println("ERROR 6");
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
System.out.println("ERROR 6.5");
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();
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
System.out.println("ERROR 7");
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(listView);
menu.findItem(R.id.action_write).setVisible(!drawerOpen);
menu.findItem(R.id.action_grabmsg).setVisible(!drawerOpen);
menu.findItem(R.id.action_mydiary).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
System.out.println("landscape");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
System.out.println("portrait");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//bundle = getIntent().getExtras();
//String language_chosen = bundle.getString("lang_pick");
if (id == R.id.action_write) {
Intent writeNewMsg = new Intent(getApplicationContext(), writeMsgActivity.class);
//writeNewMsg.putExtra("lang_pick", language_chosen);
startActivity(writeNewMsg);
}
else if(id == R.id.action_grabmsg){
Intent grabNewMsg = new Intent(getApplicationContext(), getMsgActivity.class);
//grabNewMsg.putExtra("lang_pick", language_chosen);
finish();
startActivity(grabNewMsg);
}
else if(id == R.id.action_mydiary){
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
System.out.println("ERROR 8"); //This is where the error is. It is returned but never used.
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
My problem is here:
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
System.out.println("ERROR 8"); //This is where the error is. It is returned but never used.
return true;
}
and here these methods were never called:
public void onDrawerOpened(View drawerView) {
System.out.println("ERROR 5.5");
super.onDrawerOpened(drawerView);
listView.bringToFront();
mDrawerLayout.requestLayout();
getSupportActionBar().setTitle("User Menu Option");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerClosed(View view) {
System.out.println("ERROR 6");
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
Here is the xml for the drawer called navdrawer.xml of NavigationObject class:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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>
UPDATED - STILL NEED ASSISTANCE
Here is where I use the extend on my other classes (This class do not have the drawer xml within their xml because I am inheriting from NavigationObject which has its own xml called navdrawer):
public class MainActivity extends NavigationObject implements OnClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.get_msg);
Problem: Everytime I click the option menu bar on the drawer it prints "8" from the NavigationObject class but it does nothing after that. There was no error in the code because all of the system out print I placed worked except for System.out.println("ERROR 5.5") and System.out.println("ERROR 6") which are used to open and close the drawer. The swipe does not work.
This was working when I shoved all of NavigationObject class inside my MainActivity activity class but now it's not working when I made the drawer as a separate class (NavigationObject class) for inheritance.
The menu bar is working fine. But the optionselected at "ERROR 8" does not return anything but still prints out so it's working but its doing nothing either.
Any help is very much appreciated, this is for my final year project and it's due very soon :) .
You set a different layout (R.layout.get_msg) in your derived class. Does this layout contain the NavigationDrawer? If not -- there's your bug.
Edit
Try this: Move the initialization of the NavigationDrawer to a separate method in your base activity like so:
public class NavigationObject extends ActionBarActivity ...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
}
protected void initNavigationDrawer() {
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
System.out.println("ERROR 1");
addDrawerItems();
setupDrawer();
}
And in your MainActivity call the init method in your onCreate() method, after setting the content view.
public class MainActivity extends NavigationObject ...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_msg); // <-- must contain drawer_layout
initNavigationDrawer();
}