ToolBar's Menu item is not clickable - android

I am having cart icon on ToolBar.When I try to click,it didn't show any action for a long time.After keep on clicking it, Toast message that I set is enabled or the app is crashed.
Please help me to fix it.
My Code is:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
badgeLayout = (RelativeLayout) menu.findItem(R.id.badge).getActionView();
mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
badgeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Cart is Working", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, ProductActivity.class);
startActivity(next);
}
});
return true;
}
UPDATE:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnCloseListener, SearchView.OnQueryTextListener {
public static final String MyPREFERENCES = "Preference";
public static final String SEARCHING_DATA = "DATA_SEARCH";
public static String strTabName;
public static TextView mCounter;
public static RelativeLayout badgeLayout;
public ArrayList<String> values;
Toolbar toolbar;
Context context;
Config config;
ArrayList<String> tabName = new ArrayList<String>();
SharedPreferences pref;
TextView txtDash_Title, txtDash_Des;
String passQuery;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
String possibleEmail;
String GOOGLE_USERNAME;
private int count = 0;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
pref = context.getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
setupToolbar();
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);
txtDash_Title = (TextView) findViewById(R.id.dashboard_txt_title);
txtDash_Des = (TextView) findViewById(R.id.dashboard_txt_des);
TextView myTextview = (TextView) findViewById(R.id.textView);
if (haveNetworkConnection())
new TabNameSync().execute();
else
Toast.makeText(context, "No Network Connection", Toast.LENGTH_SHORT).show();
setupCollapsingToolbar();
getGOOGLEUSERNAME();
}
private void getGOOGLEUSERNAME() {
Cursor c = getApplication().getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
c.moveToFirst();
GOOGLE_USERNAME = c.getString(c.getColumnIndex("display_name"));
Log.e("Google Username", GOOGLE_USERNAME);
c.close();
}
private void setupCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(
R.id.collapse_toolbar);
collapsingToolbar.setTitleEnabled(false);
}
private void setupToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Welcome to Scoop Shop!");
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
badgeLayout = (RelativeLayout) menu.findItem(R.id.badge).getActionView();
mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
badgeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Cart Working", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, ProductActivity.class);
startActivity(next);
}
});
// SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
// searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
// searchView.setSubmitButtonEnabled(false);
//// searchView.getOutlineProvider();
// searchView.setOnQueryTextListener(this);
// searchView.setOnCloseListener(this);
// return super.onCreateOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
break;
case R.id.badge:
Toast.makeText(context, "Cart is Working", Toast.LENGTH_SHORT).show();
/* Intent next = new Intent(context, ProductActivity.class);
startActivity(next);*/
return true;
default:
return super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
}

The issue may already be closed, but I found possible cause:
if you used Relative Layout in your .xml file, neighboring elements can cover your toolbar.
So, your toolbar must be in top of views in your .xml file.
It's working for me.

You should go with OnOptionsItemSelected()
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.badge:
Toast.makeText(context, "Cart is Working", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, ProductActivity.class);
startActivity(next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
For more information check this link: http://developer.android.com/guide/topics/ui/menus.html

May be the problem is you are not calling super.onOptionsItemSelected(item) when badge is clicked. Change your method as follows :-
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item)
switch (item.getItemId()) {
case R.id.action_search:
break;
case R.id.badge:
Toast.makeText(context, "Cart is Working", Toast.LENGTH_SHORT).show();
/* Intent next = new Intent(context, ProductActivity.class);
startActivity(next);*/
break;
default:
break;
}
return true;
}

Related

Android - display progress bar when click on any sound from listview

this is what i want but dont know how to do it.Below is the code of my main activity. I have a listview of sound clips and i want to show a progressbar and button when we click on any sound, that progress bar should indicate the progress of the respective sound clip and button shoud be change to stop icon. i am using adapterview with arraylist.i have attached an image of that
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,NavigationView.OnNavigationItemSelectedListener {
private ArrayList<String> songList;
private ListView songView;
SearchView searchView;
private MediaPlayer mp;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songList = new ArrayList<>();
mp = new MediaPlayer();
songView = findViewById(R.id.song_list);
progressBar=findViewById(R.id.progressBar);
try {
getSongList();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ArrayAdapter<String> listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, songList);
songView.setAdapter(listAdapter);
songView.setOnItemClickListener(this);
registerForContextMenu(songView);
Intent serviceIntent =
new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// code for scroll to top button
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
songView.setSelection(0);
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
IInAppBillingService mService;
ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
public void getSongList() throws IllegalAccessException {
Field[] fields = R.raw.class.getFields();
// loop for every file in raw folder
for (Field field : fields) {
int rid = field.getInt(field);
// Use that if you just need the file name
String filename = field.getName();
songList.add(filename);
songList
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void onDestroy() {
super.onDestroy();
if (mService != null) {
unbindService(mServiceConn);
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
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
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_remove_ads) {
} else if (id == R.id.nav_share) {
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "SoundBoard");
String sAux = "\nGet this app on Google Play\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.facebook.orca \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
} catch (Exception e) {
//e.toString();
}
} else if (id == R.id.nav_rate) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.facebook.orca"));
startActivity(intent);
} else if (id == R.id.about_us) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// selected item
TextView txtView = (TextView) view;
String fname = txtView.getText().toString().toLowerCase();
int resID = getResources().getIdentifier(fname, "raw", getPackageName());
Toast.makeText(getApplicationContext(), "Hello Javatpoint"+getResources().getResourceName(resID), Toast.LENGTH_SHORT).show();
MediaPlayer mediaPlayer = MediaPlayer.create(this, resID);
mediaPlayer.start();
if (mp.isPlaying()) {
mp.reset();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.song_list) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_list, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
View view = info.targetView;
TextView txtView = (TextView) view;
String fname = txtView.getText().toString().toLowerCase();
int resID = getResources().getIdentifier(fname, "raw", getPackageName());
switch (item.getItemId()) {
case R.id.share:
// add stuff here
//String sharepath=
//Uri uri = Uri.parse(view.getResources().getResourceName(resID));
//String sharePath = Environment.getExternalStorageDirectory().getPath()
// + "/Soundboard/Ringtones/custom_ringtone.ogg";
//Uri uri = Uri.parse(sharePath);
// Use this to load the file
Uri uri=Uri.parse("file://" +getResources().getResourceEntryName(resID)+".mp3");
String str=("content://"+uri);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/mp3");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM,uri);
startActivity(Intent.createChooser(share, "Share Sound File"));
return true;
case R.id.notification:
// edit stuff here
uri=Uri.parse("file://" +getResources().getResourceEntryName(resID)+".mp3");
str=("content://"+uri);
Toast.makeText(getApplicationContext(), ""+uri, Toast.LENGTH_SHORT).show();
return true;
case R.id.ringtone:
// remove stuff here
return true;
default:
return super.onContextItemSelected(item);
}
}
}

Failed to convert value of type java.util.HashMap to boolean

I'm trying to detect the connection state of my app, but this is the Error am facing:
Failed to convert value of type java.util.HashMap to boolean
I am using Firebase. The error is on line:
boolean connected = dataSnapshot.getValue(Boolean.class);
So the Error comes in the OnDataFinishedLoading() method . Data was coming at first, but now I just want to detect the apps network connection. Below is my code:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static String KEY_HEADLINES="headlines";
public static String KEY_DETAILS="details";
// private static final String TAG = "Ask Doctor App";
ProgressBar pb;
public List<NewsModel> newslist;
public NewsAdapter2 adapter;
private RecyclerView mRecyclerView;
private DatabaseReference mRef;
ImageView image_news;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// call the array list
newslist = new ArrayList<NewsModel>();
pb = (ProgressBar) findViewById(R.id.progressBarNews);
image_news =(ImageView) findViewById(R.id.image_news);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//Enabling offline capabilities
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
// firebase initialisation......
mRef = FirebaseDatabase.getInstance().getReference("News");
// keep my data synced
mRef.keepSynced(true);
OnDataFinishedLoading();
// load data
//declare the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo netInfo = cm.getActiveNetworkInfo();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* if (isOnline()) {
Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", null).show();
} else {
Snackbar.make(view, "There's a Network problem", Snackbar.LENGTH_LONG)
.setAction("", null).show();
}
Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", null).show();*/
}
});
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);
}
private void OnDataFinishedLoading(){
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
boolean connected = dataSnapshot.getValue(Boolean.class);
if(connected) {
pb.setVisibility(View.INVISIBLE);
LoadData(dataSnapshot);
} else{
Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
LoadData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void LoadData (DataSnapshot dataSnapshot){
System.out.println(dataSnapshot.getValue());
NewsModel news_model =dataSnapshot.getValue(NewsModel.class);
newslist.add(news_model);
adapter = new NewsAdapter2(MainActivity.this, newslist);
mRecyclerView.setAdapter(adapter);
}
/* protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
*/
#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
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Intent i;
if (id == R.id.hospitals) {
i = new Intent(MainActivity.this, HealthCentres.class);
startActivity(i);
} else if (id == R.id.doctors) {
i = new Intent(MainActivity.this, Doctors.class);
startActivity(i);
} /*else if (id == R.id.location) {
i = new Intent(MainActivity.this, Location.class);
startActivity(i);
} */else if (id == R.id.tips) {
i = new Intent(MainActivity.this, Tips.class);
startActivity(i);
} /*else if (id == R.id.faq) {
}
*/
/*
else if (id == R.id.suggestions) {
}
*/
else if (id == R.id.contacts) {
i= new Intent(MainActivity.this, ContactUs.class);
startActivity(i);
}
/*
else if (id == R.id.settings) {
}
*/
else if (id == R.id.about) {
i = new Intent(MainActivity.this, AboutUs.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Ok, so the core problem you're having is that Firebase is returning a Map, not a Boolean. That's because of the way you have this configured--every time a child is added, you try to look at the DataSnapshot (that's what the listener you setup does), and tries to get a Boolean value out. However, the Snapshot is the child added to the database (and not a boolean) so instead you get a map out.
If all you want to do is verify that a child was added successfully, I'd do the following:
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Object value = dataSnapshot.getValue();
if(value != null) {
pb.setVisibility(View.INVISIBLE);
LoadData(dataSnapshot);
} else{
Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();
}
}
However, this isn't really going to solve your network connectivity problem. It'll just do stuff whenever a non-null child gets added to the firebase object, which could happen frequently. Also in LoadData, you don't check to make sure that the object passed in isn't null.

hamburger is not working when i click. i have to drag for menu

This is the main activity where I have implemented the drawer and toolbar. I have tried all possible solutions on stack. I have not used the hamburger image
I created the navigation view and added it in my xml:
public class NavigationMenu extends AppCompatActivity {
DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBarDrawerToggle actionBarDrawerToggle;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;
RoundImage roundedImage;
ImageView profileImage;
TextView uname,mail;
private SQLiteHandler db;
private SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_menu);
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
/* Setting drawer in menu*/
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,R.string.drawer_open,R.string.drawer_close);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
actionBarDrawerToggle.syncState();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container,new HomeFragment());
fragmentTransaction.commit();
/* Accessing database getApplicationContext( */
db = new SQLiteHandler(this);
HashMap<String,String> user = db.getUserDetails();
String id = user.get("id");
String name = user.get("name");
String email = user.get("email");
Log.d("Soulsystem", name);
Log.d("Soulsystem", email);
/*Access navigation header here to set name and to call the attributes of header*/
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
View header = navigationView.getHeaderView(0);
uname = (TextView)header.findViewById(R.id.rahul);
uname.setText(name);
AppController.getInstance().setClientConsultancyDetails(id,name,email);
profileImage = (ImageView)header.findViewById(R.id.navigation_view_Image);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
profile();
}
});
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.contact:
contact();
break;
case R.id.logout:
logoutUser();
/* item.setChecked(true);
drawerLayout.closeDrawers();*/
break;
}
return true;
}
});
}
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
actionBarDrawerToggle.syncState();
super.onPostCreate(savedInstanceState);
}
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
Intent intent = new Intent(NavigationMenu.this, MainActivity.class);
startActivity(intent);
}
//call to Profile image fragment
private void profile(){
Log.d("NavigationMenu", "In profile Image view");
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new ClientProfile());
fragmentTransaction.commit();
drawerLayout.closeDrawers();
}
//call to Contact image fragment
private void contact(){
Log.d("NavigationMenu", "In profile Image view");
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new Contact());
fragmentTransaction.commit();
drawerLayout.closeDrawers();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.drawe_menu, menu);
return false;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.menu.drawe_menu);
item.setVisible(false);
super.onPrepareOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try listening to toolbar
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
drawerLayout.openDrawer(GravityCompat.START);
}
}
});

Setting title of the toolbar when a navigation item menu is clicked

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!

Material design: naviagtion drawer with tabs and recyclerview

I have a problem with the navigation drawer. I want to know how to display recyclerview when the user clicks on different element of each menu.
Here are some source code and an illustrative capture
N.B: different menu items ("Accueil, Contacts Staff, etc ...") are in an .xml file in the layout.
MainActiviy.java
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
setupWindowAnimations();
//définir la toolbr en tant qu'actionbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, 0, 0);
drawerLayout.setDrawerListener(drawerToggle);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
//on remplit notre viewpager, comme à notre habitude
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
return RecyclerViewFragment.newInstance();
}
#Override
public CharSequence getPageTitle(int position) {
return "Tab " + position;
}
#Override
public int getCount() {
return 1;
}
});
//indique au tablayout quel est le viewpager à écouter
tabLayout.setupWithViewPager(viewPager);
}
private void setupWindowAnimations() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Explode explode = new Explode();
getWindow().setExitTransition(explode);
Fade fade = new Fade();
getWindow().setReenterTransition(fade);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#OnClick(R.id.fab)
public void onFabClick() {
Snackbar.make(fab, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}).show();
}
}
Sample source code for you
public class NavActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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 onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Hope this helps you
Not understand exactly what you want. Where do you want to display recycler view? You already have OnNavigationItemSelectedListener, just check which menu you have clicked and do what you want:
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
 case R.id.contact:
// do anything you want, ex
showContactList();
break;
}
the function to show your contact list
private void showContactList(){
List<Contact> data = getYourDataSomeHow();
yourAdapter.setData(data);
yourRecyclerView.setAdapter(yourAdapter);
}

Categories

Resources