I have created a DrawerLayout and it works fine. But I want it to close when the user touches the background. This can be implemented with a DrawerLayout with listView but here i'm using a NavigationView. So is there a way to accomplish this?
Here is the menu layout for the NavigationView
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/home" android:title="Home Parent" android:icon="#drawable/ic_home_black"/>
<item android:id="#+id/send" android:title="Send" android:icon="#drawable/ic_send_black"/>
<item android:id="#+id/add" android:title="Add" android:icon="#drawable/ic_add_black"/>
</menu>
Here is the java code
public class ParentActivity extends AppCompatActivity {
private NavigationView mNavigationView;
private User mCurrentUser;
private UserLocalStore mUserLocalStore;
private CircleImageView mProfilePic;
private TextView mProfileName;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parent);
mUserLocalStore = new UserLocalStore(this);
mCurrentUser = mUserLocalStore.getUserDetails();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavigationView = (NavigationView)findViewById(R.id.navigationView);
setNavigationViewMenu(mCurrentUser.userType);
mProfileName = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.profileName);
mProfileName.setText(mCurrentUser.getName());
mProfilePic = (CircleImageView) mNavigationView.getHeaderView(0).findViewById(R.id.circleImageProfile);
Picasso.with(this).load("https://www.sonypark360.net/wp-content/uploads/2017/08/profile-pictures.png").into(mProfilePic);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
mDrawerLayout.closeDrawers();
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void setNavigationViewMenu(String userType) {
switch (userType){
case "s":
mNavigationView.inflateMenu(R.menu.menu_student_navigation_drawer);
break;
case "pa":
mNavigationView.inflateMenu(R.menu.menu_parent_navigation_drawer);
break;
case "pr":
mNavigationView.inflateMenu(R.menu.menu_principal_navigation_drawer);
break;
case "t":
mNavigationView.inflateMenu(R.menu.menu_teacher_navigation_drawer);
break;
}
}
}
Here is the DrawerLayout code
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mlpj.www.morascorpions.ParentActivity">
<android.support.design.widget.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header_layout"
>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
I have also looked into this question, but it does not solve my problem
Try this
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Rect viewRect = new Rect();
mNavigationView.getGlobalVisibleRect(viewRect);
if (!viewRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
//hide your navigation view here.
}
return super.dispatchTouchEvent(ev);;
}
Related
Menu Item click not working I tried various things but it won't work.
Here are my code:
Home Activity:
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private Button mBtRequest;
private Button mBtContinue;
private ProfileFragment mProfileFragment;
private SetPreferences Setpref;
private SlideUp slideUp;
private View dim;
private View sliderView;
Toast toast;
private TextView mTvDrawerName;
private TextView mTvDrawerMobile;
private TextView mtoolbarTitle;
private String mfullName;
private String mMobile;
private SharedPreferences mSharedPreferences;
private CompositeSubscription mSubscriptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
Setpref = new SetPreferences(this);
if (!Setpref.IsLoggined()) {
gotoMain();
finish();
}
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
mSubscriptions = new CompositeSubscription();
initSharedPreferences();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.findViewById(R.id.toolbar_title).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mBtRequest = (Button) findViewById(R.id.btn_request);
mBtContinue = (Button) findViewById(R.id.btn_continue);
mBtRequest.setOnClickListener(view -> slideUp());
mBtContinue.setOnClickListener(view -> checkout());
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);
sliderView = findViewById(R.id.slideView);
sliderView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (toast != null){
toast.cancel();
}
toast = Toast.makeText(HomeActivity.this, "click", Toast.LENGTH_SHORT);
toast.show();
}
});
dim = findViewById(R.id.dim);
slideUp = new SlideUpBuilder(sliderView)
.withListeners(new SlideUp.Listener.Events() {
#Override
public void onSlide(float percent) {
dim.setAlpha(1 - (percent / 100));
}
#Override
public void onVisibilityChanged(int visibility) {
if (visibility == View.GONE){
// fab.show();
}
}
})
.withStartGravity(Gravity.BOTTOM)
.withLoggingEnabled(true)
.withGesturesEnabled(true)
.withStartState(SlideUp.State.HIDDEN)
.build();
Typeface myraid_bold = Typeface.createFromAsset(getAssets(),"fonts/MyriadPro-Bold_0.otf");
Typeface myraid_semibold = Typeface.createFromAsset(getAssets(),"fonts/MyriadPro-Semibold_0.otf");
View header = navigationView.getHeaderView(0);
mTvDrawerName = (TextView) header.findViewById(R.id.nav_user_name);
mTvDrawerMobile = (TextView) header.findViewById(R.id.nav_mobile_number);
mtoolbarTitle = (TextView) findViewById(R.id.toolbar_title);
mTvDrawerName.setText(mfullName);
mTvDrawerMobile.setText(mMobile);
mTvDrawerName.setTypeface(myraid_bold);
mTvDrawerMobile.setTypeface(myraid_bold);
mtoolbarTitle.setTypeface(myraid_semibold);
mBtRequest.setTypeface(myraid_bold);
mBtContinue.setTypeface(myraid_bold);
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mfullName = mSharedPreferences.getString(Constants.FULLNAME,"");
mMobile = mSharedPreferences.getString(Constants.MOBILE,"");
}
private void gotoProfile(){
if (mProfileFragment == null) {
mProfileFragment = new ProfileFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragmentFrame,mProfileFragment,ProfileFragment.TAG).commit();
}
private void gotoMain(){
Setpref.setIsLoggined(false);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
private void slideUp(){
slideUp.show();
}
private void checkout(){
}
#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);
}
private void logout() {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(Constants.MOBILE,"");
editor.putString(Constants.TOKEN,"");
editor.putString(Constants.FULLNAME,"");
editor.apply();
gotoMain();
}
private void showSnackBarMessage(String message) {
Snackbar.make(findViewById(R.id.drawer_layout),message,Snackbar.LENGTH_SHORT).show();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_my_addresses) {
// Handle the camera action
} else if (id == R.id.nav_my_orders) {
} else if (id == R.id.nav_refer) {
} else if (id == R.id.nav_logout) {
logout();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
activity_home_drawer.xml
<?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_my_addresses"
android:icon="#drawable/ic_location_on_white_24px"
android:title="My Addresses" />
<item
android:id="#+id/nav_my_orders"
android:icon="#drawable/ic_history_white_24px"
android:title="My Orders" />
<item
android:id="#+id/nav_refer"
android:icon="#drawable/ic_record_voice_over_white_24px"
android:title="Refer & Earn" />
</group>
<group
android:id="#+id/menu_bottom"
android:checkableBehavior="none">
<item
android:id="#+id/nav_logout"
android:icon="#drawable/ic_exit_to_app_white_24px"
android:title="Logout" />
</group>
</menu>
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Aashish Kaushik"
android:id="#+id/nav_user_name"
android:textColor="#android:color/white"/>
<TextView
android:id="#+id/nav_mobile_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9910454530"
android:textColor="#android:color/white"/>
</LinearLayout>
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout
android:alpha="0"
android:id="#+id/dim"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dimBg" />
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_home_drawer" />
<!-- The Fragment -->
<FrameLayout
android:id="#+id/fragmentFrame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.DrawerLayout>
When I try to view activity_home.xml as a design it will not showing left drawer but when I install the app on device it will show the left drawer on click but when I click on any time it will not showing check able box and not working.
Update These lines of code works for me.. after update clean and rebuild Project.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
Here is a simple solution to address this issue. You can just link your HomeActivity methods to the menu items (whichever you want to). Now just create your methods and go to the menu layout. In the menu layout just add the android:onClick inside the item tag and put the particular method name inside it. And you are done. Let me know if this was useful.
I have a trouble with my app. I want to make an app that has WebView and will change the URL when I click one of the items on the navigation drawer. For example:
Facebook
Twitter
Github
and so on. But I couldn't implement the onClick event. I am new in Android development. Thanks in advance.
This is my Java File
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolBar;
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolBar = (Toolbar) findViewById(R.id.nav_action_bar);
setSupportActionBar(mToolBar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("https://www.facebook.com/groups/276912206003690/");
webView.setWebViewClient(new WebViewClient());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if(webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
}
This my Main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tehedligmail.navigation_drawer.MainActivity"
android:id="#+id/drawer_layout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout = "#layout/navigation_action_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webView">
</WebView>
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
app:headerLayout="#layout/navigation_header"
android:layout_gravity = "start">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
This is my Menu file menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/settings"
android:icon="#mipmap/ic_launcher"
android:title="Settings" />
<item
android:id="#+id/log_out"
android:title="Log out"
android:icon="#mipmap/ic_launcher"/>
<item
android:id="#+id/google"
android:title="google"
android:icon="#mipmap/ic_launcher"/>
</menu>
Your MainActivity needs to implement NavigationView.OnNavigationItemSelectedListener and override onNavigationItemSelected
Create an instance of NavigationView(e.g. mNavigationView) and bind it to your view.
Set listener as mNavigationView.setNavigationItemSelectedListener(this);
Override onNavigationItemSelected()
Here's how that method looks:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.settings) {
//do something
} else if (id == R.id.log_out){
//do something
} else if (id == R.id.google) {
//do something
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
I have made a navigation drawer in Android in which I want to implement onClick for it. This is my main activity:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle aToggle;
private Toolbar toolbar;
private RecyclerView recyclerView;
private RecyclerAdapter recyclerAdapter;
private RecyclerView.Adapter adapter;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
aToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.navig, R.string.open, R.string.Close);
navigationView = (NavigationView) findViewById(R.id.nav_view);
mDrawerLayout.addDrawerListener(aToggle);
toolbar = (Toolbar) findViewById(R.id.nav_action);
toolbar.setNavigationIcon(R.drawable.navig);
setSupportActionBar(toolbar);
aToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setItemIconTintList(null);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerAdapter = new RecyclerAdapter(getApplicationContext());
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (aToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}}
This is my XML layout for the activity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alpit.formula2.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="0dp"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="58dp"
android:orientation="vertical"></android.support.v7.widget.RecyclerView>
<android.support.v7.widget.Toolbar
android:id="#+id/nav_action"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#EF6C00"
android:orientation="vertical"
android:theme="#style/ThemeOverlay.AppCompat.Dark"></android.support.v7.widget.Toolbar>
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFA726"
app:menu="#menu/navigation_menu"
app:theme="#style/NavigationTheme">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
This is my menu items:
<group
android:id="#+id/gp1"
android:checkableBehavior="single">
<item
android:id="#+id/nav_maths"
android:icon="#drawable/maths"
android:title="Maths" />
<item
android:id="#+id/nav_physics"
android:icon="#drawable/physics"
android:title="Physics" />
<item
android:id="#+id/nav_chem"
android:icon="#drawable/chem"
android:title="Chemistry" />
<item
android:id="#+id/EEE"
android:icon="#drawable/lightbulb"
android:title="Electronics Electrical" />
</group>
<group
android:id="#+id/gp2"
android:checkableBehavior="single">
<item
android:id="#+id/unitconversion"
android:icon="#drawable/unitconversion"
android:title="Unit Conversion" />
<item
android:id="#+id/Scientist"
android:icon="#drawable/scientist"
android:title="Scientist" />
<item
android:id="#+id/favourite"
android:icon="#drawable/favourite"
android:title="Favourite" />
</group>
<group
android:id="#+id/gp3"
android:checkableBehavior="single">
<item
android:id="#+id/Share"
android:icon="#drawable/share"
android:title="Share" />
<item
android:id="#+id/Rate"
android:icon="#drawable/rate"
android:title="Rate" />
<item
android:id="#+id/ads"
android:icon="#drawable/ad"
android:title="Remove Ads" />
<item
android:id="#+id/aboutus"
android:icon="#drawable/aboutus"
android:title="About Us" />
</group>
</menu>
The problem is I am not able to understand how to implement the onClick on the navigation drawer as it is populated by the list given by us not by any listView.
How can I implement onClick on the items of navigation drawer?
You need to add implements NavigationView.OnNavigationItemSelectedListener
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
and add method
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.nav_maths: {
//do somthing
break;
}
}
//close navigation drawer
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
method to set Listener
private void setNavigationViewListener() {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
call method in onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setNavigationViewListener()
}
Add NavigationItemSelectedListener event to nav_view
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Implement your Activity with NavigationView.OnNavigationItemSelectedListener
and add this code for click 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;
}
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val nav_view: NavigationView = findViewById(R.id.nav_view)
nav_view.setNavigationItemSelectedListener(this)
nav_view.bringToFront();
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.miid_log_out -> Toast.makeText(this, "Working", Toast.LENGTH_SHORT).show()
}
return false
}
}
in your
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (aToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}}
add these lines:
switch (item.getItemId()) {
case R.id.nav_maths:
// your logic here.
return true;
case R.id.nav_physics:
//your logic here
return true;
default:
return super.onOptionsItemSelected(item);
}
Below code is for adding toggle to DrawerLayout
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);
And to add listener to Navigation menu items
implements NavigationView.OnNavigationItemSelectedListener
and override below method
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if(id == R.id. nav_maths){
//Handle your stuff here
}
}
Add below code to onCreate method
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Step-1: Extends the NavigationView.OnNavigationItemSelectedListener on your Activity
Step2:
Then there will show an error then override the method:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
return false;
}
get the Id with menuItem.getId() .And Perform Your Action as per your need.
final Step: Add This line in onCreate navigationView.setNavigationItemSelectedListener(this);
That's it.
binding.navigationView.setNavigationItemSelectedListener {
when(it.itemId){
R.id.book -> Toast.makeText(applicationContext, "Booked", Toast.LENGTH_SHORT).show()
}
true
}
fab=(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
}
I have this menu layout "navigation_menu.xml":
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/item1"
android:title="#string/item1"/>
<item
android:id="#+id/item2"
android:title="#string/item2"/>
<item
android:id="#+id/item3"
android:title="#string/item3"/>
</menu>
My main activity layout "activity_main.xml" is this:
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:layout_gravity="start">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
And this is the Java code of the main activity where I initialize the drawer:
private DrawerLayout drawer_layout;
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
drawer_layout = (DrawerLayout)findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer_layout, R
.string.open_drawer, R.string.close_drawer);
drawer_layout.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
The drawer opens and closes correctly, but I don't know how to do something when an item is clicked, for example showing a log.
Does anyone know?
Thanks
Use onNavigationItemSelected() method to handle Navigation Drawer Item Click. See Below Code.
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// ...
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mNavigationView.setNavigationItemSelectedListener(this);// you need to set Listener.
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item)
{
// mDrawer.closeDrawer(GravityCompat.START);
switch (item.getItemId()) {
case R.id.item1: {
}
break;
case R.id.item2: {
}
break;
case R.id.item3: {
}
break;
}
return true;
}
My app has two activities with a DrawerLayout and a NavigationView (android.support.design.widget.NavigationView).
I use an app theme with parent Theme.AppCompat.Light.DarkActionBar, and for my Lollipop emulator, there are no problems.
But for my Jellybean device and emulator, I have a very strange behaviour:
The background of the NavigationView items is sometimes rendered as light grey (which would be ok for me), sometimes as a light blue shade (I think it's the Theme Holo default).
For my "real" app, the grey tint would always appear on the first drawer and the blue tint always on the other one. At first I thought the difference may be due to some detail like the first uses an ActionBarDrawerToggle and the other one doesn't, so maybe I had to somehow set the android:listSelector for the second one only.
So I created a MCVE-like sample and noticed that both drawers show both tints now and then. Is this a bug or am I missing something?
What can I do to get rid of Theme Holo?
Screenshots:
By the way, I have the same random behaviour for the ActionButton background:
My code (~ 95% of it for those who like to run their own tests):
activity_main.xml just a 'Blank Activity' with a big "Hello World" at the center:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<TextView
android:text="#string/hello_world"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
activity_main_decor.xml
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"/>
<android.support.design.widget.NavigationView
android:id="#+id/main_drawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/menu_main_drawer"/>
</android.support.v4.widget.DrawerLayout>
activity_other.xml
<merge>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Hello again!"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
</merge>
activity_other_decor.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout android:id="#+id/container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<include layout="#layout/activity_other"/>
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/other_drawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="end"
app:menu="#menu/menu_other_drawer" />
</android.support.v4.widget.DrawerLayout>
MainActivity - the navigation drawer has to appear from the left and above the ActionBar( BTW thanks to #Peter Cai for some very useful lines )
public class MainActivity extends AppCompatActivity
{
private static final String TAG = "StyleForDrawers main";
private static final String DRAWER_OPEN = "main_drawer_open";
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle drawerToggle;
private boolean isDrawerOpen;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initNavDrawer();
}
private void initNavDrawer()
{
final SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(this);
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
drawerLayout = (DrawerLayout) inflater.inflate(R.layout.activity_main_decor, null);
ViewGroup decor = (ViewGroup)activity.getWindow().getDecorView();
View child = decor.getChildAt(0);
decor.removeView(child);
FrameLayout container = (FrameLayout)drawerLayout.findViewById(R.id.container);
container.addView(child);
decor.addView(drawerLayout);
navigationView = (NavigationView) findViewById(R.id.main_drawer);
navigationView.setItemTextColor(ContextCompat.getColorStateList(this, R.color.nav_item));
navigationView.setItemTextAppearance(R.style.MyNavdrawerTextAppearance);
View headerView = navigationView.inflateHeaderView(R.layout.navdrawer_list_header);
// header View should appear below status bar, so set padding:
(headerView.findViewById(R.id.nav_header_root)).setPadding(0, getStatusbarHeight(), 0, (int) getResources().getDimension(R.dimen.activity_vertical_margin));
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
{
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
Intent intent = null;
int id = menuItem.getItemId();
if (id == R.id.action_other_activity)
{
intent = new Intent(MainActivity.this, OtherActivity.class);
}
// -- skipped some code for Help etc. --
drawerLayout.closeDrawer(navigationView);
isDrawerOpen = false;
if (intent != null)
{
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
return true;
}
});
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.sDrawerOpen, R.string.sDrawerClose)
{
#Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
sPrefs.edit().putBoolean(DRAWER_OPEN, false).apply();
}
#Override
public void onDrawerOpened(View drawerView)
{
isDrawerOpen = true;
super.onDrawerOpened(drawerView);
sPrefs.edit().putBoolean(DRAWER_OPEN, true).apply();
}
};
drawerLayout.setDrawerListener(drawerToggle);
if (getSupportActionBar() != null)
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.nav_drawer);
}
if (sPrefs.getBoolean(DRAWER_OPEN, true)) // open at first launch
{
drawerLayout.openDrawer(navigationView);
}
else
{
drawerLayout.closeDrawer(navigationView);
}
}
#Override
protected void onPause()
{
super.onPause();
SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sPrefs.edit().putBoolean(DRAWER_OPEN, isDrawerOpen).apply();
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
public static int getStatusbarHeight()
{
int retValue = 0;
int resID = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resID > 0) {
retValue = getResources().getDimensionPixelSize(resID);
}
return retValue;
}
}
OtherActivity - the drawer is like a context menu and appears from the right without overlapping the ActionBar:
public class OtherActivity extends AppCompatActivity
{
private static final String TAG = "StyleForDrawers other";
private static final String DRAWER_OPEN = "other_drawer_open";
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
private boolean mIsDrawerOpen;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other_decor);
initMenuDrawer();
}
private void initMenuDrawer()
{
final SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.other_drawer);
mNavigationView.setItemTextColor(ContextCompat.getColorStateList(this, R.color.nav_item));
mNavigationView.setItemTextAppearance(R.style.MyNavdrawerTextAppearance);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
{
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
int id = menuItem.getItemId();
if (id == R.id.action_back_to_main)
{
finish();
}
// -- skipped some code for doing something (else) --
mDrawerLayout.closeDrawer(mNavigationView);
mIsDrawerOpen = false;
return true;
}
});
mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener()
{
#Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
mIsDrawerOpen = true;
sPrefs.edit().putBoolean(DRAWER_OPEN, true).apply();
}
#Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
mIsDrawerOpen = false;
sPrefs.edit().putBoolean(DRAWER_OPEN, false).apply();
}
});
if (sPrefs.getBoolean(DRAWER_OPEN, false)) // don't open at first launch
{
mDrawerLayout.openDrawer(mNavigationView);
}
else
{
mDrawerLayout.closeDrawer(mNavigationView);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_other, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_opendrawer)
{
if (mIsDrawerOpen)
{
mDrawerLayout.closeDrawer(mNavigationView);
}
else
{
mDrawerLayout.openDrawer(mNavigationView);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
menu_main.xml unnecessary
menu_other.xml contains an action button to open/close the drawer:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/action_opendrawer"
android:title="open/close drawer"
android:icon="#drawable/nav_drawer"
android:orderInCategory="100"
app:showAsAction="always"/>
</menu>
styles.xml
<resources>
<color name="accent_orange">#ff6d00</color>
<color name="my_background">#eeeeee</color>
<color name="my_text">#311b92</color>
<color name="my_sec_text">#B1311b92</color>
<color name="my_actionbar">#1a237e</color>
<color name="my_statusbar">#1a237e</color>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#color/my_actionbar</item>
<item name="colorPrimaryDark">#color/my_statusbar</item>
<item name="colorAccent">#ffc400</item>
<item name="android:windowBackground">#color/my_background</item>
<item name="android:textColorPrimary">#color/my_text</item>
<item name="android:textColor">#color/my_text</item>
<item name="android:textColorSecondary">#color/my_sec_text</item>
</style>
<style name="MyNavdrawerTextAppearance" parent="TextAppearance.AppCompat.Small">
<item name="android:textStyle">bold</item>
</style>
</resources>
UPDATE (May 2016)
Meanwhile I've also tried setting my own background for the NavigationView items. The background is changed but on touching I still get a ripple for Lollipop and higher (which is ok) and unfortunately still the alternating effect on Jellybean, probably from some kind of list selector which I don't know how to manipulate.
UPDATE 2 (September 2016)
I installed a new version of Android Studio, am using the newest versions of build tools and all the libraries (24.0.2 respectively 24.2.0) and even ditched the ActionBar in favour of Toolbar. The last means I won't have to use the hack in Main to get the nav drawer to cover the ActionBar, so I'm not using a LayoutInflater in my code any more.
But still no luck :(
I'm pretty sure that this is a bug: the same code behaving differently from one app run to the next and the inconsistency between activities Main and Other during one and the same run.