I'm new and I'm learning to use the Android Studio Navigation Drawer Activity Template code (mainMenu.java)
to start this project
I've created another Empty Activity (viewProfile.java) so that it can be called when user press the Navigation Drawer menu. Example: User press 'View Profile' inside the menu.
I need help on how to have a single Navi Drawer menu in all my activities, like viewProfile.java Activity.
Tried copying all codes related to Navi Drawer from mainMenu.java and paste into viewProfile.java. Doesnt work at all, sadly.
I've commented some of the codes that I have tried.
mainMenu.java
public class mainMenu extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//Defining views
private TextView editTextUserName;
private TextView textView_profile_name;
private TextView textView_profile_email;
private TextView textView_profile_amount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
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();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile) {
Toast.makeText(this, "nav_profile", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_listing) {
startActivity(new Intent(this, ViewAllStock.class));
} else if (id == R.id.nav_history) {
Toast.makeText(this, "nav_history", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_coming) {
Toast.makeText(this, "nav_coming", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_logout) {
logout();
} else if (id == R.id.nav_setting) {
Toast.makeText(this, "nav_setting", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
viewProfile.java
public class viewProfile extends AppCompatActivity implements ListView.OnItemClickListener, NavigationView.OnNavigationItemSelectedListener {
private ListView listView;
private String JSON_STRING;
private SwipyRefreshLayout mSwipyRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_stock);
// 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(ViewAllStock.this);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile) {
// Handle the camera action
Toast.makeText(ViewAllStock.this, "nav_profile", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_listing) {
Toast.makeText(ViewAllStock.this, "nav_listing", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_history) {
Toast.makeText(ViewAllStock.this, "nav_history", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_coming) {
Toast.makeText(ViewAllStock.this, "nav_coming", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_logout) {
Toast.makeText(ViewAllStock.this, "nav_logout", Toast.LENGTH_SHORT).show();;
} else if (id == R.id.nav_setting) {
Toast.makeText(ViewAllStock.this, "nav_setting", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
It is advisable to use multiple fragments rather than activities in such a case. But even if you still want to use different activities then simply include navigation drawer in other activities the same way you implemented in one of them. However this leads to writing of same piece of code multiple times, which should be avoided.
Use Fragments and containers so that if you would like to change the layout you can change only part of layout not the entire layout.So your navigation drawer remains safe through out your app.
You should use fragments for this and you can get lots of demo for this.. and if still you wanna use activity you have to include nevigation in every layout like this
<?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" >
<RelativeLayout
android:layout_width="match_parent"
android:background="#drawable/bg"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<include
android:id="#+id/toolbar_offr"
layout="#layout/toolbar_offer" />
</LinearLayout>
<ListView
android:id="#+id/OfferFragLV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/ll1">
</ListView>
</RelativeLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.phoenix.spicejunction.frag.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_below="#id/mainRL"
android:layout_gravity="start"
android:layout_marginTop="50dp"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
and here is my fragment_navigation_drawer layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:layout_marginTop="40dp"
>
<RelativeLayout
android:id="#+id/nav_header_container"
android:layout_width="match_parent"
android:layout_height="145dp"
android:layout_alignParentTop="true"
android:background="#fff"
android:gravity="center" >
<com.phoenix.spicejunction.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profileIV"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/_10sdp"
android:src="#drawable/ic_launcher"
app:civ_border_color="#color/my_yellow"
app:civ_border_width="3dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/profileIV"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:text="TextView"
android:textColor="#000" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/_5sdp"
android:text="AGE: "
android:textColor="#000" />
</RelativeLayout>
<!--
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/nav_header_container"
android:layout_marginTop="15dp" />
-->
<ListView
android:id="#+id/home_listDrawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/nav_header_container"
android:layout_gravity="start"
android:layout_marginTop="5dp"
android:entries="#array/slider_array" />
</RelativeLayout>
and i am using this this method
#Override
public void onDrawerItemSelected(View view, int position) {
base.displayView(position);
}
so you have to implemenmt this method in every activity and by calling any activity make them finish..
Related
I'm working on a menu navigation drawer , in that I'm not able to click items when I'm adding a constraint layout inside the drawer layout. But after removing that click, the menu item works fine. So please tell me how can I fix this issue.
here below is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
tools:context=".MainActivity"
android:id="#+id/drawerlayout"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include layout="#layout/appbar">
</include>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigationitem"
android:id="#+id/navigationview"
app:headerLayout="#layout/header_layout"
android:layout_gravity="start">
</com.google.android.material.navigation.NavigationView>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:textColor="#color/white">
</TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.drawerlayout.widget.DrawerLayout>
And here below is my mainactivity
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
Toolbar toolbar1;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout=findViewById(R.id.drawerlayout);
toolbar1=findViewById(R.id.tbar);
navigationView=findViewById(R.id.navigationview);
toolbar1.inflateMenu(R.menu.navigationitem);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar1,R.string.nav_open,R.string.nav_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id==R.id.profile){
Toast.makeText(MainActivity.this, "Profile", Toast.LENGTH_SHORT).show();
}
else if(id==R.id.contact){
Toast.makeText(MainActivity.this, "Contact", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Logoutact", Toast.LENGTH_SHORT).show();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
});
}
}
Now, How Can Solve This Problem?
I have created the layout as attached below, I haven't used any drawerlayout or navigation view. top bar is created using toolbar tag. Now I want to add a navigation view which will invoke once user clicks that hamburger icon. And it should be accessible from other activities as well
You should use the navigation drawer.
You can do this this by creating one common class named BaseActivity and put your code of navigation drawer in this class. and extend your classes/Activities with BaseActivity, where you want to show navigation drawer.
public class BaseActivity extends AppCompatActivity {
public Toolbar toolbar;
ActionBarDrawerToggle mDrawerToggle;
Context context;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected boolean useToolbar() {
return true;
}
#Override
public void setContentView(int layoutResID) {
context = this;
DrawerLayout fullView = (DrawerLayout) getLayoutInflater().inflate(R.layout.drawer_main, null);
FrameLayout activityContainer = (FrameLayout) fullView.findViewById(R.id.frame);
getLayoutInflater().inflate(layoutResID, activityContainer, true);
super.setContentView(fullView);
toolbar = (Toolbar) fullView.findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
toolbar.setTitle("");
this.getSupportActionBar().setElevation(0);
getSupportActionBar().setLogo(R.drawable.ic_arrahm);
// toolbar.setLogo(R.drawable.ic_main);
if (useToolbar()) {
setSupportActionBar(toolbar);
setTitle("Places Near Me");
} else {
toolbar.setVisibility(View.GONE);
}
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
case R.id.edit_profile:
return true;
case R.id.change_password:
return true;
default:
Toast.makeText(getApplicationContext(), "Work in progress", Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
View header = navigationView.getHeaderView(0);
TextView tvName = (TextView) header.findViewById(R.id.name);
TextView tvEmail = (TextView) header.findViewById(R.id.email);
String name = Preferences.getDataFromStringPreferences(context,Constants.USER_DETAILS, Constants.USER_NAME);
if (name != null) {
tvName.setText(name);
}
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return mDrawerToggle.onOptionsItemSelected(item);
}
}
create drawer_main.xml layout file
<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/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/tool_bar"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
create toolbar.xml under layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
>
</android.support.v7.widget.Toolbar>
create drawer_header.xml layout resource file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="178dp"
android:background="#color/colorPrimary"
android:orientation="vertical"
android:padding="20dp"
android:weightSum="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text=""
android:textColor="#ffffff"
android:textSize="14sp"
android:textStyle="bold"
/>
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text=""
android:textColor="#ffffff"
android:textSize="14sp"
android:textStyle="normal"
/>
</LinearLayout>
<ImageView
android:id="#+id/circleView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="30dp" />
</RelativeLayout>
This question already has answers here:
Clicking hamburger icon on Toolbar does not open Navigation Drawer
(1 answer)
on clicking hamburger icon navigation drawer not opening
(2 answers)
Closed 3 years ago.
The drew the red line to show where the orange line should keep going.
After searching similar questions, I could not find a way to solve my problem.
I have a toggle button that shows in my Activity but when I press it, it doesn't open the navigation drawer (if I slide my finger it opens).
*The toggle button shows in the activity (the toolbar is transparent)
OnCreate and onOptionsItemSelect
ActionBarDrawerToggle toggle;
DrawerLayout drawer;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle
(
this,
drawer,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
{
};
drawer.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("");
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.colorPrimaryDark));
FloatingActionButton fab = findViewById(R.id.action_btn);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), NewEventActivity.class);
startActivity(intent);
/*Intent intent = new Intent(getApplicationContext(), testes.class);
startActivity(intent);*/
}
});
navigationView = findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(toggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
XML code:
<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=".MainActivity"
android:id="#+id/drawer_layout">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title=""
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/wrapper_layout">
</LinearLayout>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/action_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:backgroundTint="#FE7D4B"
app:srcCompat="#drawable/ic_add" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/drawer_menu"
android:layout_gravity="start"
android:id="#+id/navigation_view"
>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
This question already has answers here:
NavigationView get/find header layout
(9 answers)
Closed 5 years ago.
I have a DrawerLayout in my android app that has a NavigationView which is using a nav_header_main2 layout. Inside the nav_header_main2 layout file there is an ImageView and 2 TextViews, in my MainActivity I am trying to grab those TextView items so I can dynamically fill in the content with the username and email address, however I am always getting a null reference whenever I try to access them.
Here is the main layout file...
<?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">
<include
layout="#layout/app_bar_main2"
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_main2"
app:menu="#menu/activity_main2_drawer"/>
</android.support.v4.widget.DrawerLayout>
As you can see, the NavigationView is using "nav_header_main2", here is that file...
<?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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/menu_user_photo"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/ic_person_white"
app:border_color="#color/colorTransparent"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="3dp"
android:layout_marginBottom="0dp"
app:border_width="1dp"/>
<!--<ImageView-->
<!--android:id="#+id/imageView"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:paddingTop="#dimen/nav_header_vertical_spacing"-->
<!--app:srcCompat="#android:drawable/sym_def_app_icon"/>-->
<TextView
android:id="#+id/menu_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:text="Android Studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"/>
<TextView
android:id="#+id/textView"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio#android.com"/>
</LinearLayout>
Then in my MainActivity, I have tried multiple ways of accessing the "menu_username" item but all of them return a null reference. Here is my main class right now...
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public static final String EXTRA_MESSAGE = "text.notreal.justatest.MESSAGE";
public static final int TAG_KEY = 0;
public static final int TAG_VALUE = 0;
public List<Post> posts = new ArrayList<>();
public FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", 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);
//THIS IS WHAT IS FAILING
//I HAVE ALSO TRIED JUST USING findViewById(R.id.menu_username); NULL STILL
TextView menuUserName = (TextView) navigationView.findViewById(R.id.menu_username);
if(menuUserName == null) {
Log.d("MAIN ACTIVITY", "Somehow the menu_username doesn't exist");
}
if(findViewById(R.id.frameLayout) != null) {
if(savedInstanceState != null) {
return;
}
AllPostsFragment fragment = new AllPostsFragment();
fragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.frameLayout, fragment).commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
default:
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;
}
}
As you can see I am trying to grab it using the NavigationView object, which doesn't work, but I have also tried just using
TextView menuUsername = (TextView) findViewById(R.id.menu_username);
which also returns a null reference. How can I get the username and email fields in my main activity so I can dynamically fill in the content? Thank you
You won't find it that way. The proper way is first to find your NavigationView, then get its HeaderView using getHeaderView() and then search your widgets in that HeaverView:
NavigationView nv = findViewById(R.id.nav_view);
TextView menuUsername = nv.getHeaderView(0).findViewById(R.id.menu_username);
or more compact way
TextView menuUsername = findViewById(R.id.nav_view)
.getHeaderView(0).findViewById(R.id.menu_username);
I'm working the first time with Fragments, so sorry if I did smt very stupid :D
I have a Navigation Drawer Activity. When I click in it on the first item i want to open a Fragment. When I open it, there is not only the Layout of the Fragment shown, but also the layout of my MainActivity, it looks very strange.
[1]: https://i.stack.imgur.com/iqTAq.png MainActivity
[2]: https://i.stack.imgur.com/kULQY.png Navigation Drawer
[3]: https://i.stack.imgur.com/T2vDJ.png First Fragment
How can I solve the problem?
Here is my code if you need it:
MainActivity(Navigation Drawer Templated, I wrote only in the onNavigationItemSelected, so that it goes to the fragment when I click on the first item:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", 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);
}
#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();
if (id == R.id.nav_camera) {
setTitle("First Fragment");
first first = new first();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment, first).commit();
} 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;
}
}
content_main (It should belong to MainActivity)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.gsr.fragmenttest.MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is the Mainactivity, no fragemnt"/>
</FrameLayout>
</RelativeLayout>
First Fragment Activity
public class first extends Fragment {
Button btn;
TextView textView;
public first() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
btn=(Button)v.findViewById(R.id.button);
textView=(TextView)v.findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView.setText("Nice, it works !!");
}
});
// Inflate the layout for this fragment
return v;
}
}
And at least the fragment layout file
<FrameLayout 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"
tools:context="com.gsr.fragmenttest.first">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Hello Fragment"
android:textSize="50dp"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
</FrameLayout>
I hope someone can help me :)
Add a background to your fragment layout, it should solve your problem.
<FrameLayout 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"
android:background="#color/white" //Your background color
tools:context="com.gsr.fragmenttest.first">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
...
I think the problem is in your activity layout
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
try to change your main activity layout like above. Hope it will solve your problem.
1) implements first.OnOnFragmentInteractionListener
2) in onNavigationItemSelected method put this code
if (id == R.id.nav_camera) {
setTitle("First Fragment");
first first = new first();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment, new first()).commit();
3)In first fragment use this line
import android.app.Fragment;