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
Related
I am A Beginner in android development, actually I have a Navigation drawer with Fragments my issue is when i go to fragment b from a the state in navigation drawer is updating to fragment b successfully but when go to fragment B From Fragment A by on 'backpressed' method the drawer item state is not updating / changing to fragment A . please help me in fixing this.
Here is my Main Activity Code :
public class MainActivity extends AbsRuntimePermission implements NavigationView.OnNavigationItemSelectedListener {
//, GoogleApiClient.OnConnectionFailedListener {
private static final int REQUEST_PERMISSION = 10;
private Toolbar toolBar;
private NavigationView navDrawer;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
private View btnLogOut;
private int selectedItem;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
// private GoogleApiClient googleApiClient;
private FloatingActionButton fab;
private CoordinatorLayout coordinatorLayout;
private HomeFragment homeFragment=new HomeFragment();
final String TAG = this.getClass().getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
auth = FirebaseAuth.getInstance();
final FirebaseUser user = auth.getCurrentUser();
String userID = user.getUid();
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Contact_FAB.class);
startActivity(intent);
}
});
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main_content, homeFragment);
tx.commit();
final WebView webView = (WebView) findViewById(R.id.WV);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
public void onPageFinished(WebView view, String url) {
// do your stuff here}
#Override
public void onReceivedError (WebView view,int errorCode, String description, String
failingUrl){
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
webView.loadUrl("https://google.co.in");
requestAppPermissions(new String[] {
Manifest.permission.READ_CONTACTS,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
R.string.msg,REQUEST_PERMISSION);
toolBar =(Toolbar)
findViewById(R.id.app_bar);
setSupportActionBar(toolBar);
// If a notification message is tapped, any data accompanying the notification
// message is available in the intent extras. In this project the launcher
// intent is fired when the notification is tapped, so any accompanying data would
// be handled here. If you want a different intent fired, set the click_action
// field of the notification message to the desired intent. The launcher intent
// is used when no click_action is specified.
//
// Handle possible data accompanying notification message.
if(
getIntent().
getExtras() !=null)
{
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
if (key.equals("AnotherActivity") && value.equals("True")) {
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("value", value);
startActivity(intent);
finish();
}
}
}
// subscribeToPushService();
drawerLayout =(DrawerLayout)
findViewById(R.id.drawer_layout);
navDrawer =(NavigationView)
findViewById(R.id.menu_drawer);
navDrawer.setNavigationItemSelectedListener(this);
drawerToggle =new
ActionBarDrawerToggle(this,drawerLayout, toolBar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
selectedItem =savedInstanceState ==null?R.id.nav_item_1 :savedInstanceState.getInt("selectedItem");
}
#Override
public boolean onNavigationItemSelected (MenuItem menuItem){
menuItem.setChecked(true);
selectedItem = menuItem.getItemId();
Fragment fragment = null;
switch (selectedItem) {
case R.id.nav_item_1:
fragment = new HomeFragment();
break;
case R.id.nav_item_2:
fragment = new MicrosoftDskFragment();
break;
case R.id.nav_item_3:
fragment = new GoogleDskFragment();
break;
case R.id.nav_item_4:
fragment = new AppleDskFragment();
break;
case R.id.nav_item_5:
fragment = new OthersDskFragment();
break;
case R.id.nav_item_6:
fragment = new MobiSpecsFragment();
break;
case R.id.nav_item_8:
Intent intent = new Intent(MainActivity.this, About.class);
startActivity(intent);
break;
default:
break;
}
if (!DetectConnection.checkInternetConnection(MainActivity.this)) {
Toast.makeText(MainActivity.this, "Plz check your network connectivity", Toast.LENGTH_SHORT).show();
} else {
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_content, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
boolean twice = false;
#Override
public void onBackPressed () {
DrawerLayout layout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (layout.isDrawerOpen(GravityCompat.START)) {
layout.closeDrawer(GravityCompat.START);
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
Log.d(TAG, "click");
if (twice == true) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
twice = true;
Log.d(TAG, "twice: " + twice);
//super.onBackPressed();
Toast.makeText(MainActivity.this, "Please Press Again To Exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
Log.d(TAG, "twice: " + twice);
}
}, 3000);
}
}
}
#Override
public boolean onKeyDown ( int keyCode, KeyEvent event){
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
homeFragment.OnKeyDown(keyCode);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#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 super.onCreateOptionsMenu(menu);
}
#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.profile) {
Intent intent = new Intent(MainActivity.this, Profile.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState){
super.onSaveInstanceState(outState, outPersistentState);
outState.putInt("selectedItem", selectedItem);
}
#Override
public void onPermissionsGranted ( int requestCode){
//Do anything when permisson granted
// Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_LONG).show();
}
/* #Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
*/
}
}
When you popBackStack() the fragment from back stack will appear on screen so you need to listen for Back stack changes.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.containerFrame);
if (fragment != null) {
// check for fragment and set the drawer state
if(fragment instanceof Frag1){
// set drawer state for 1
}else if(fragment instanceof Frag2){
// set drawer state for 2
}
}
}
});
Our application android use a lot of memory in MainActivity ( 32MB )
we don't know how to detect and specify where is exactly the problem
we try to comment all the code in MainActivity but No solution
Can someone help us to detect where the solution exactly in our Code ?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ArrayList<String> CodeBar = new ArrayList<>();
private ArrayList<Integer> id_Four = new ArrayList<>() ;
private ArrayList<String> nomProd = new ArrayList<>() ;
private ArrayList<String> prix = new ArrayList<>() ;
private ArrayList<String> nomFour = new ArrayList<>() ;
private ArrayList<String> adresse = new ArrayList<>() ;
private ArrayList<String> tel = new ArrayList<>() ;
private ArrayList<String> description = new ArrayList<>() ;
private ArrayList<Float> ratings = new ArrayList<>() ;
private ArrayList<Integer> images;
private BitmapFactory.Options options;
private ViewPager viewPager;
private View btnNext, btnPrev;
private FragmentStatePagerAdapter adapter;
private LinearLayout thumbnailsContainer;
private ShineButton deleteLast;
private final static ArrayList<Integer> resourceIDs = new ArrayList<>();
Intent historiqueIntent;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView title = (TextView) findViewById(R.id.title_promo);
title.setTypeface(title.getTypeface(), Typeface.ITALIC);
deleteLast =(ShineButton)findViewById(R.id.deleteAll);
final MaterialSpinner spinner_search = (MaterialSpinner) findViewById(R.id.spinner);
// final Spinner spinner_search = (Spinner) findViewById(R.id.spinner);
ShineButton btn_search = (ShineButton) findViewById(R.id.searchView);
// spinner_search.setDropdownHeight(1000);
spinner_search.setDropdownMaxHeight(1000);
historiqueIntent = new Intent(MainActivity.this , Histourique.class);
//ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.Ville,android.R.layout.simple_spinner_dropdown_item);
// spinner_search.setAdapter(adapter);
VilleRemember vill = new VilleRemember(getBaseContext() , "" , 0 );
spinner_search.setSelectedIndex(vill.getindiceSelected());
spinner_search.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
#Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
VilleRemember vill = new VilleRemember(getBaseContext() , item,position );
vill.newSelectedVille(position,item);
}
});
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(historiqueIntent);}});
activity=this;
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//rotateAnimation(fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lanceScane(activity);
}
});
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);
}
#Override
protected void onResume()
{
// System.gc();
super.onResume();
}
//////////////////////////////////////
Timer timer;
int page = 1;
public void pageSwitcher(int seconds) {
timer = new Timer(); // At this line a new Thread will be created
timer.scheduleAtFixedRate(new RemindTask(), 0, seconds * 1000); // delay
// in
// milliseconds
}
// this is an inner class...
class RemindTask extends TimerTask {
#Override
public void run() {
// As the TimerTask run on a seprate thread from UI thread we have
// to call runOnUiThread to do work on UI thread.
runOnUiThread(new Runnable() {
public void run() {
if (page >= 4) { // In my case the number of pages are 5
// timer.cancel();
page = 0;
// viewPager.setCurrentItem(page--);
// Showing a toast for just testing purpose
/* Toast.makeText(getApplicationContext(), "Timer stoped",
Toast.LENGTH_LONG).show(); */
} else {
viewPager.setCurrentItem(page++);
}
}
});
}
}
#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.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
int id = item.getItemId();
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();
if (id == R.id.accueil) {
// Handle the camera action
} else if (id == R.id.historique) {
Intent i = new Intent(this , Histourique.class);
startActivity(i);
} else if (id == R.id.prefere) {
Intent i = new Intent(this , Fav_class.class);
startActivity(i);
//overridePendingTransition(R.anim.slide_in_bottom,R.anim.slide_out_bottom);
} else if (id == R.id.parametre) {
Intent i = new Intent(this , Parametres.class);
startActivity(i);
} else if (id == R.id.propose_nous) {
startActivity(new Intent(MainActivity.this, About_us.class));
finish();
} else if (id == R.id.contactez_nous) {
Intent i = new Intent(this , contact_us.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void lanceScane(Activity activity)
{
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scanner");
integrator.setCameraId(0);
integrator.setBeepEnabled(true);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
//historiqueIntent = new Intent(MainActivity.this , Histourique.class);
//historiqueIntent.putExtra("serial",result.getContents());
//startActivity(historiqueIntent);
Intent i = new Intent(MainActivity.this,RechercheResult1.class);
i.putExtra("CodeBar",result.getContents());
Historique his = new Historique(this , result.getContents());
his.insert(result.getContents());
his.remplireDateCode();
startActivity(i);
Toast.makeText(this, "Done! " , Toast.LENGTH_SHORT).show();
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onPause()
{
// System.gc();
super.onPause();
}
//------------------------------------------------------
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i > 0) {
//next page
if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount() - 1) {
page++;
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
} else {
//previous page
if (viewPager.getCurrentItem() > 0) {
page--;
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
}
};
}
// images dyal les produit proposses :
private void inflateThumbnails() {
System.out.println("==========>"+CodeBar.size());
TextView title = (TextView) findViewById(R.id.title_promo);
if(CodeBar.size() == 0)
{
title.setVisibility(View.INVISIBLE);
deleteLast.setVisibility(View.INVISIBLE);
}
else
{
title.setVisibility(View.VISIBLE);
deleteLast.setVisibility(View.VISIBLE);
}
thumbnailsContainer.removeAllViews();
for (int i = 0; i < CodeBar.size(); i++) {
View imageLayout = getLayoutInflater().inflate(R.layout.cardview, null);
TextView price = (TextView) imageLayout.findViewById(R.id.prixprodtestcard);
TextView name = (TextView) imageLayout.findViewById(R.id.nomprodtestcard);
TextView namfou=(TextView) imageLayout.findViewById(R.id.qtestockcard);
TextView rating=(TextView)imageLayout.findViewById(R.id.rating);
ImageView imageProd = (ImageView) imageLayout.findViewById(R.id.imageprodcard);
FloatingActionButton btnlike = (FloatingActionButton) imageLayout.findViewById(R.id.likeButtoncard);
btnlike.setVisibility(View.INVISIBLE);
price.setText(prix.get(i));
name.setText(nomProd.get(i));
namfou.setText(nomFour.get(i));
rating.setText(ratings.get(i).toString());
imageProd.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow View pager to intercept touch events.
System.out.print("=============>ACTION_DOWN");
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
System.out.print("=============>ACTION_UP");
// Allow View pager to intercept touch events.
// v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle Listview touch events.
v.onTouchEvent(event);
return true;
}
});
Glide.with(this)
.load(new TagDatabase().URL_IMAGFOU+"fid="+id_Four.get(i)+"&&code="+CodeBar.get(i)+"&&etat= -99")
.diskCacheStrategy( DiskCacheStrategy.NONE )
.skipMemoryCache( true )
.placeholder(R.drawable.waitloat)
.thumbnail(0.1f)
.into(imageProd);
imageProd.setOnClickListener(onChagePageClickListener(i));
thumbnailsContainer.addView(imageLayout);
}
}
private View.OnClickListener onChagePageClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),InformationsProduit.class);
intent.putExtra("nomProd", nomProd.get(i));
intent.putExtra("prix", prix.get(i));
intent.putExtra("nomFour",nomFour.get(i));
intent.putExtra("etatpromo", -99);//attttt
intent.putExtra("telFour",tel.get(i));
intent.putExtra("addrFour",adresse.get(i));
intent.putExtra("idFour",id_Four.get(i));
intent.putExtra("description",description.get(i));
intent.putExtra("codeBar",CodeBar.get(i));
startActivity(intent);
}
};
}
}
I have some slides with ViewPager that shows application help and I want to show it in DrawerLayout too.
this is HelpActivity.class:
public class HelpActivity extends Activity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
prefManager = new PrefManager(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.fragment_help);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_1,
R.layout.welcome_2,
R.layout.welcome_3,
R.layout.welcome_4,
R.layout.welcome_5,
R.layout.welcome_6,
R.layout.welcome_7};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(HelpActivity.this, MainActivity.class));
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(/*getString(R.string.start)*/ "Start");
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(/*getString(R.string.next)*/ "Next");
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
this is PrefManager.class:
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "stand up-welcome";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
and I use this code for defining it to drawerLayout:
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
with clicking on help in drawer, nothing shows. what should I do?
This is MainActivity.class:
ublic class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public Toolbar toolbar;
public NavigationView navigationView;
public ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new HomeFragment());
tx.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle= setupDrawerToggle();
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//navigation view
navigationView= (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(navigationView);
actionBarDrawerToggle.syncState();
// default item of navigation view
// navigationView.getMenu().getItem(0).setChecked(true);
navigationView.setCheckedItem(R.id.nav_item_home);
}//onCreate
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()==R.id.nav_item_setting){
startActivityForResult(new Intent(this, SettingActivity.class), 1002);
}
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
} return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState); // `onPostCreate` called when activity start-up is complete after `onStart()`
}
#Override
public void onBackPressed() {
MainActivity.this.finish();
}
}
in your xml:
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#drawable/background_drawer"
app:headerLayout="#layout/nav_header"
app:itemIconTint="#color/colorPrimary"
app:menu="#menu/menu_navigation" />
you have to add help options in your menu_navigation
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_item_help"
android:icon="#drawable/profile_icon"
android:title="Help" />
</group>
</menu>
Also in your MainActivity:
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_setting:
Intent i = new Intent(MainActivity.this, SettingActivity.class);
startActivity(i);
break;
case R.id.nav_item_help:
Intent i = new Intent(MainActivity.this, HelpActivity.class);
startActivity(i);
break;
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
In your preference manager:
public void setFirstTimeLaunch(boolean isFirstTime) {
Editor editor = pref.edit();
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
difference between startactivity and startActivityForResult is:
1. startActvity():
startActivity() will start the activity you want to start without worrying about getting any result from new child activity started by startActivity to parent activity.
2. startAcitvityForResult():
startAcitvityForResult() starts another activity from your activity and it expect to get some data from newly started child activity by startAcitvityForResult() and return that to parent activity.
see this blog:https://malikshafique.wordpress.com/2012/06/14/android-startactivity-and-startactivityforresult/
In my app I have the following navigationview.
So when the user click the menu item Καλώς ήρθες(meaning welcome in Greek),I want the this to be shown in the toolbar. This is my code for the navigationview.
public class Welcome extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private SessionManager session;
Toolbar toolbar;
private int mIconSize;
private String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
session = new SessionManager(getApplicationContext());
SharedPreferences userName = PreferenceManager.getDefaultSharedPreferences(this);
//UserId = userName.getString("id","");
username = userName.getString("user_name", "");
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
if (savedInstanceState == null) {
//Restore the fragment's instance and geo coordinates!
//homeFragment = (FragmentHome) getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
setSelected(R.id.welcome);
}else{
//profileFragment = (FragmentProfile) fm2.findFragmentByTag(PROFILE_FRAGMENT);
}
ActionBarDrawerToggle adt = new ActionBarDrawerToggle(this,drawerLayout,toolbar,
R.string.open_drawer,R.string.close_drawer){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.addDrawerListener(adt);
adt.syncState();
navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setBackgroundColor(getResources().getColor(R.color.navigation_bg_color));
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
drawerLayout.closeDrawers();
boolean result = setSelected(item.getItemId());
return result;
}
});
View v = navigationView.getHeaderView(0);
TextView t = (TextView)v.findViewById(R.id.username);
t.setText(username);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.log_out, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.log_out:
logoutUser();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logoutUser() {
session.setLogin(false);
// Launching the login activity
Intent intent = new Intent(Welcome.this, MainActivity.class);
startActivity(intent);
finish();
}
public boolean setSelected(int selected) {
switch (selected){
case R.id.welcome:
WelcomeFragment welcomeFragment = new WelcomeFragment();
FragmentManager fm1 = getSupportFragmentManager();
FragmentTransaction fragmentTra1 = fm1.beginTransaction();
fragmentTra1.replace(R.id.content,welcomeFragment);
//fragmentTra1.addToBackStack("added");
fragmentTra1.commit();
return true;
case R.id.general:
GeneralFragment generalFragment= new GeneralFragment();
FragmentManager fm2 = getSupportFragmentManager();
FragmentTransaction fragmentTra2 = fm2.beginTransaction();
fragmentTra2.replace(R.id.content,generalFragment);
//fragmentTra1.addToBackStack("added");
fragmentTra2.commit();
return true;
case R.id.announcements:
AnnouncementsFragment announcementsFragment= new AnnouncementsFragment();
FragmentManager fm3 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubOne = fm3.beginTransaction();
fragmentTraSubOne.replace(R.id.content,announcementsFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubOne.commit();
return true;
case R.id.sub_one:
NewsFragment newsFragment= new NewsFragment();
FragmentManager fm4 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubTwo = fm4.beginTransaction();
fragmentTraSubTwo.replace(R.id.content,newsFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubTwo.commit();
return true;
case R.id.sub_two:
FanClubFragment fanClubFragment= new FanClubFragment();
FragmentManager fm5 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubThree = fm5.beginTransaction();
fragmentTraSubThree.replace(R.id.content,fanClubFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubThree.commit();
return true;
}
return false;
}
public static Intent newIntent(Context context) {
return new Intent(context,MainActivity.class);
}
#Override
public void onBackPressed() {
if(isNavDrawerOpen()){
closeDrawerLayout();
}else {
super.onBackPressed();
}
}
public boolean isNavDrawerOpen() {
return drawerLayout!=null && drawerLayout.isDrawerOpen(GravityCompat.START);
}
private void closeDrawerLayout(){
if(drawerLayout != null){
drawerLayout.closeDrawer(GravityCompat.START);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
return (keyCode == KeyEvent.KEYCODE_BACK ? true :
super.onKeyDown(keyCode, event));
}
}
Any ideas?
Thanks,
Theo.
Try using setTitle():
public boolean setSelected(int selected) {
switch (selected){
case R.id.welcome:
toolbar.setTitle("Welcome");
......
}
.....
}
Try using:
getSupportActionBar().setTitle("title");
in the switch-case
I think you could use something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, ID, POSITION, TEXT);
item.setIcon(R.drawable.drawable_resource_name);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
Also this link might help: Here
Hope it helps ;)
btw your app looks great!
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.