android - nothing happening when navigation drawer icon is tapped - android

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.

Related

add slider menu in navigation drawer

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

Drawer functionality in android just like paytm

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);
}
}

App crashes on orientation change in android

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);
}
...

NavigationDrawer and Up Navigation

I implemented a BaseActivity which extends the ActionBarActivity and implements a NavigationDrawer. All my Activities are inheriting from this BaseActivity.
Im now wondering if i can implement a NavigationDrawer and still have the proper up navigation using the toolbar or is the device back button supposed to work as the up navigation button when i implemented a NavigationDrawer?
EDIT:
Custom NavigationDrawer with Toolbar
public abstract class NavigationActivity extends ActionBarActivity {
private Toolbar toolbar = null;
private DrawerLayout drawerLayout = null;
private ActionBarDrawerToggle drawerToggle = null;;
private ListView listView = null;
private CharSequence drawerTitle = null;
private CharSequence title = null;
private NavigationDrawerConfiguration navigationConfig = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.navigationConfig = this.getNavigationDrawerConfiguration();
this.setContentView(this.navigationConfig.getMainLayout());
this.toolbar = (Toolbar) this.findViewById(R.id.app_bar);
this.drawerLayout = (DrawerLayout) this.findViewById(navigationConfig.getDrawerLayoutId());
this.listView = (ListView) this.findViewById(navigationConfig.getLeftDrawerId());
this.listView.setAdapter(navigationConfig.getBaseAdapter());
this.listView.setOnItemClickListener(new DrawerItemClickListener());
this.drawerTitle = this.getTitle();
this.title = this.getTitle();
this.setSupportActionBar(this.toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.getSupportActionBar().setHomeButtonEnabled(true);
this.drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, this.toolbar, this.navigationConfig.getDrawerOpenDesc(), this.navigationConfig.getDrawerCloseDesc()) {
#Override
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(title);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(drawerTitle);
invalidateOptionsMenu();
}
};
this.drawerLayout.setDrawerListener(this.drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
this.drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
this.drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (this.navigationConfig.getActionMenuItemsToHideWhenDrawerOpen() != null) {
boolean drawerOpen = this.drawerLayout.isDrawerOpen(listView);
for (int item : this.navigationConfig.getActionMenuItemsToHideWhenDrawerOpen()) {
menu.findItem(item).setVisible(!drawerOpen);
}
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (this.drawerToggle.onOptionsItemSelected(item)) {
return true;
} else {
return false;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
if (this.drawerLayout.isDrawerOpen(this.listView)) {
this.drawerLayout.closeDrawer(this.listView);
} else {
this.drawerLayout.openDrawer(this.listView);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
protected NavigationDrawerConfiguration getNavigationDrawerConfiguration() {
NavigationDrawerItem[] menu = new NavigationDrawerItem[] {
// NavigationMenuSection.create(100, "Demos"),
NavigationMenuItem.create(100, "Item 1", "ic_measure", false, this),
NavigationMenuItem.create(200, "Item 2", "ic_list", false, this),
// NavigationMenuSection.create(200, "General"),
NavigationMenuItem.create(300, "Item 3", "ic_diagrams", false, this),
NavigationMenuItem.create(400, "Item 4", "ic_calculator", false, this),
NavigationMenuItem.create(500, "Item 5", "ic_scanner", false, this),
NavigationMenuItem.create(600, "Item 6", "ic_profile", false, this),
NavigationMenuItem.create(700, "Item 7", "ic_follower", false, this),
NavigationMenuItem.create(800, "Item 8", "ic_settings", false, this)
};
NavigationDrawerConfiguration navigationDrawerConfiguration = new NavigationDrawerConfiguration();
navigationDrawerConfiguration.setMainLayout(R.layout.activity_menu_slide);
navigationDrawerConfiguration.setDrawerLayoutId(R.id.menu_slide_layout);
navigationDrawerConfiguration.setLeftDrawerId(R.id.menu_slide_list);
navigationDrawerConfiguration.setNavigationItems(menu);
navigationDrawerConfiguration.setDrawerOpenDesc(R.string.open_navigation_drawer);
navigationDrawerConfiguration.setDrawerCloseDesc(R.string.close_navigation_drawer);
navigationDrawerConfiguration.setBaseAdapter(new NavigationDrawerAdapter(this, R.layout.activity_menu_slide_item_row, menu));
return navigationDrawerConfiguration;
}
public void selectItem(int position) {
NavigationDrawerItem selectedItem = this.navigationConfig.getNavigationItems()[position];
this.onNavigationItemSelected(selectedItem.getId());
this.listView.setItemChecked(position, true);
if (selectedItem.updateActionBarTitle()) {
this.setTitle(selectedItem.getLabel());
}
if (this.drawerLayout.isDrawerOpen(this.listView)) {
this.drawerLayout.closeDrawer(this.listView);
}
}
protected void onNavigationItemSelected(int id) {
Intent intent = null;
switch ((int) id) {
case 100:
intent = new Intent(this, MeasureDataActivity.class);
break;
case 200:
intent = new Intent(this, MeasureDataListActivity.class);
break;
case 300:
intent = new Intent(this, DiagramsActivity.class);
break;
case 400:
intent = new Intent(this, CalcActivity.class);
break;
case 500:
intent = new Intent(this, RecipeActivity.class);
break;
case 600:
intent = new Intent(this, ProfileActivity.class);
break;
case 700:
intent = new Intent(this, FollowerActivity.class);
break;
case 800:
intent = new Intent(this, SettingsActivity.class);
break;
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
protected int getDrawerIcon() {
return R.drawable.ic_navigation_drawer;
}
protected DrawerLayout getDrawerLayout() {
return this.drawerLayout;
}
protected ActionBarDrawerToggle getDrawerToggle() {
return this.drawerToggle;
}
#Override
public void setTitle(CharSequence title) {
this.title = title;
this.getSupportActionBar().setTitle(title);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
/**
*
*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
}
I think in the onCreate after the super() call you can do this:
mDrawerToggle.setDrawerIndicatorEnabled(false);
If this alone doesn't work (or just doesn't work) try this:
getActionBar().setDisplayHomeAsUpEnabled(true);
Follow this link: Missing Up navigation icon after switching from ICS ActionBar to Lollipop Toolbar
Original poster found this link

unable to use handler, getting looper.prepare error

I was trying to use handler in onPageFinished method of onCreateView method of PlanetFragment class. But I am getting looper.prepare() error. Please help. And also please tell if there is some better method to use progressbar.
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
static Handler progressBarHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch (item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available,
Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet,
container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources()
.getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(
planet.toLowerCase(Locale.getDefault()), "drawable",
getActivity().getPackageName());
final WebView webview = ((WebView) rootView
.findViewById(R.id.image));
final ProgressBar progressbar = ((ProgressBar) rootView
.findViewById(R.id.progressbar));
webview.getSettings().setJavaScriptEnabled(true);
final PlanetFragment activity = this;
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
view.setVisibility(View.GONE);// hide the webview that will
// display your dialog
new Thread(new Runnable() {
private int progressBarStatus = 0;
private int fileSize;
public void run() {
progressBarHandler = new Handler();
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doWork();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressbar
.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private int doWork() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
} else if (fileSize == 200000) {
return 40;
} else if (fileSize == 300000) {
return 50;
} else if (fileSize == 200000) {
return 60;
} else if (fileSize == 300000) {
return 70;
} else if (fileSize == 200000) {
return 80;
} else if (fileSize == 300000) {
return 90;
}
}
return 100;
}
}).start();
}
#Override
public void onPageFinished(WebView view, String url) {
progressBarHandler = new Handler();
webview.loadUrl("javascript:document.getElementsByClassName('header')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('icon-anon')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('search')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_ad')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('cse_x')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_search')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_ad')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_ad')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('footer_random_button')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('mw-mf-page-left')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('mw-mf-viewport')[0].style.display=\"none\";");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Code here will run in UI thread
}
},1000);
webview.getSettings().setJavaScriptEnabled(false);
view.setVisibility(View.VISIBLE);
// you might need this
view.bringToFront();
}
});
webview.loadUrl(planet);
getActivity().setTitle(planet);
return rootView;
}
}
}
You have to create handler in Activity
just initialize the Handler in onCreate method of activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBarHandler = new Handler();
// rest of your code
and remove the initialization in Fragment class as it is already initialized in Activity . Just Use progressBarHandler in Fragment Class and it will work fine.

Categories

Resources