How can I add drawerLayout and not to damage existed LinerLayout style? - java

I began doing a project without DrawableLayout. I am using mostly LinearLayout. I want to add drawer navigation android, and as I know, I need DrawableLayout.
How can I add this, and not damage everything I have now?

Well don't be afraid. It's not so difficult. Just follow the following steps to get it:-
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_green_dark">
<!-- put you linear layout here --!>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
android:id="#+id/nv">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Navigation Header:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#color/colorPrimaryDark">
<ImageView
android:layout_width="180dp"
android:layout_height="130dp"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:background="#drawable/ic_android_black_24dp"/>
</LinearLayout>
**Create a menu for the navigation drawer**
Right-click the res folder →Select new →Android resource file →Choose ‘menu’ under the resource type drop-down list.
Name the file as ‘navigation_menu.xml’ and copy-paste the following code into the file.
`<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/account"
android:icon="#drawable/ic_portrait_black_24dp"
android:title="My Account"/>
<item android:id="#+id/settings"
android:icon="#drawable/ic_brightness_high_black_24dp"
android:title="Settings"/>
<item android:id="#+id/mycart"
android:icon="#drawable/ic_local_grocery_store_black_24dp"
android:title="My Cart"/>
</menu>
** Lastly, in you activity:** <br>
In this last and final step, we will write Java code in the MainActivity.java file.
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private DrawerLayout dl;
private ActionBarDrawerToggle t;
private NavigationView nv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dl = (DrawerLayout)findViewById(R.id.activity_main);
t = new ActionBarDrawerToggle(this, dl,R.string.Open, R.string.Close);
dl.addDrawerListener(t);
t.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nv = (NavigationView)findViewById(R.id.nv);
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch(id)
{
case R.id.account:
Toast.makeText(MainActivity.this, "My Account",Toast.LENGTH_SHORT).show();break;
case R.id.settings:
Toast.makeText(MainActivity.this, "Settings",Toast.LENGTH_SHORT).show();break;
case R.id.mycart:
Toast.makeText(MainActivity.this, "My Cart",Toast.LENGTH_SHORT).show();break;
default:
return true;
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(t.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}`

Related

I am trying to access navigation drawer so that when i click on the top left corner of app bar, I can access settings in a new activity

I am trying to access navigation drawer so that when i click on the top left corner of app bar, I can access settings in a new activity. Right now what I get when I click on the upper left corner and then click settings is the menu retracts and nothing else happens. I have a bottom navigation bar also. Please help. Here's what I have so far:
NavigationActivity.java
package com.tt.lateoclock;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.database.DatabaseReference;
import com.tt.lateoclock.Prevalent.Prevalent;
import com.tt.lateoclock.ui.findFood.FindFoodFragment;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.RecyclerView;
import de.hdodenhof.circleimageview.CircleImageView;
public class NavigationActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, BottomNavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
NavigationView navigationView;
Menu menu;
private DatabaseReference merchantRef;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
ActionBarDrawerToggle toggle;
Intent settingsIntent;
NavController navController;
AppBarConfiguration appBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
//merchantRef = FirebaseDatabase.getInstance().getReference().child("Merchants");
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Home");
drawer = findViewById(R.id.container);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = findViewById(R.id.nav_view);
BottomNavigationView navView = findViewById(R.id.bot_nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_find_food, R.id.navigation_favorites, R.id.navigation_map, R.id.navigation_receipts, R.id.navigation_settings)
.build();
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
View headerView = navigationView.getHeaderView(0);
TextView name = (TextView)headerView.findViewById(R.id.username);
CircleImageView user_image = (CircleImageView)headerView.findViewById(R.id.user_image);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id=menuItem.getItemId();
Toast.makeText(getApplicationContext(), id, Toast.LENGTH_SHORT).show();
//it's possible to do more actions on several items, if there is a large amount of items I prefer switch(){case} instead of if()
if (id==R.id.navigation_settings){
Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_SHORT).show();
}
//This is for maintaining the behavior of the Navigation view
NavigationUI.onNavDestinationSelected(menuItem, navController);
//This is for closing the drawer after acting on it
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
name.setText(Prevalent.currentUser.getName());
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController=Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onBackPressed()
{
if(drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.navigation_settings:
settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_find_food:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new FindFoodFragment()).commit();
break;
case R.id.navigation_favorites:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new com.tt.lateoclock.ui.favorites.FavoritesFragment()).commit();
break;
case R.id.navigation_receipts:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new com.tt.lateoclock.ui.receipts.ReceiptsFragment()).commit();
break;
case R.id.navigation_settings:
Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT).show();
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT).show();
return true;
}
return true;
}
}
activity_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NavigationActivity">
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_marginTop="?android:attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/mobile_navigation" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimaryDark"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bot_nav_view"
android:layout_width="match_parent"
android:layout_height="196dp"
android:layout_below="#id/nav_host_fragment"
android:layout_marginTop="-100dp"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottom_nav_menu" >
</com.google.android.material.bottomnavigation.BottomNavigationView>
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
bottom_nav_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_find_food"
android:icon="#drawable/ic_local_dining_black_24dp"
android:title="#string/title_find_food" />
<item
android:id="#+id/navigation_favorites"
android:icon="#drawable/ic_favorite_black_24dp"
android:title="#string/title_favorites" />
<item
android:id="#+id/navigation_map"
android:icon="#drawable/ic_map_black_24dp"
android:title="#string/title_map" />
<item
android:id="#+id/navigation_receipts"
android:icon="#drawable/ic_receipt_black_24dp"
android:title="#string/title_receipts" />
</menu>
drawer_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/nav_message"
android:title="Message"
android:icon="#drawable/ic_message"/>
<item android:id="#+id/nav_profile"
android:title="Profile"
android:icon="#drawable/ic_profile"/>
<item android:id="#+id/navigation_settings"
android:title="Settings"
android:icon="#drawable/ic_settings_black_24dp"
android:enabled="true"/>
</menu>
mobile_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/mobile_navigation"
app:startDestination="#+id/navigation_find_food">
<fragment
android:id="#+id/navigation_find_food"
android:name="com.tt.lateoclock.ui.findFood.FindFoodFragment"
android:label="#string/title_find_food"
tools:layout="#layout/fragment_find_food" />
<fragment
android:id="#+id/navigation_favorites"
android:name="com.tt.lateoclock.ui.favorites.FavoritesFragment"
android:label="#string/title_favorites"
tools:layout="#layout/fragment_favorites" />
<fragment
android:id="#+id/navigation_map"
android:name="com.tt.lateoclock.ui.map.MapFragment"
android:label="#string/title_map"
tools:layout="#layout/fragment_map" />
<fragment
android:id="#+id/navigation_receipts"
android:name="com.tt.lateoclock.ui.receipts.ReceiptsFragment"
android:label="#string/title_receipts"
tools:layout="#layout/fragment_receipts" />
</navigation>
Just change the activity_navigation.xml to
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
...>
<RelativeLayout...>
<com.google.android.material.navigation.NavigationView
android:layout_gravity="start"
.../>
</androidx.drawerlayout.widget.DrawerLayout>
Also you have to handle the click on the settings item with navigationView.setNavigationItemSelectedListener.
About the DrawerLayout check the doc:
Note: When using NavigationUI, the top app bar helpers automatically transition between the drawer icon and the Up icon as the current destination changes. You don't need to use ActionBarDrawerToggle.
In your code remove the code about the ActionBarDrawerToggle and use:
AppBarConfiguration appBarConfiguration =
new AppBarConfiguration.Builder(...........)
.setDrawerLayout(drawerLayout)
.build();
You can add an <activity> destination to your navigation graph for starting another activity:
<activity
android:id="#+id/navigation_settings"
android:name="com.your.package.SettingsActivity" />
Then, the default behavior of setupWithNavController() / onNavDestinationSelected() will start your activity for you. You wouldn't need to write any custom code or manual calls to setNavigationItemSelectedListener to get this behavior.
You should also strongly consider adding menuCategory="secondary" to your navigation_settings menu item as per the onNavDestinationSelected() documentation to avoid your current destination from being popped off the back stack.
Here your Setting activity is not a part of the NavigationGraph (i.e. not a fragment it's a separate activity).
And when you hit the drawer burger and choose the Setting, it won't go to the Setting as you didn't launch the intent on the OnNavigationItemSelectedListener of the NavigationView
To fix that:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id=menuItem.getItemId();
Toast.makeText(getApplicationContext(), id, Toast.LENGTH_SHORT).show();
//it's possible to do more actions on several items, if there is a large amount of items I prefer switch(){case} instead of if()
if (id==R.id.navigation_settings){
Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_SHORT).show();
Intent settingsIntent = new Intent(NavigationActivity.this, SettingsActivity.class); // <<< Here is the change
startActivity(settingsIntent); // <<< Here is the change
}
//This is for maintaining the behavior of the Navigation view
NavigationUI.onNavDestinationSelected(menuItem, navController);
//This is for closing the drawer after acting on it
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
Update
Replace
navigationView.setNavigationItemSelectedListener(this);
With
navView.setNavigationItemSelectedListener(this);
Add the OnClick method in the menu item
<item
android:id="#+id/nav_whats_app"
android:icon="#drawable/ic_menu_settings"
android:title="#string/menu_settings"
android:onClick="onOpenSettings" />
Then add the method in the activity like this
//Kotlin Android
fun onOpenSettings(item: MenuItem) {
//... open settings here
}
Java Code
//Java Android
void onOpenSettings(MenuItem item) {
//... open settings here
}
To close any Navigation drawer, just call
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
}

How to use own layout for navigation drawer activity instead of auto generated layout?

I have a navigation drawer activity, that have automatically generated these activity_student_home2, app_bar_student_home, content_student_home, nav_header_student_home layout files. I have separately created activity_student_home layout.By default the activity java class has the acitivity_student_home2 layout as setContentView. But instead, I want to use the acitivity_student_home layout. If I try to change the setContentView to acitivity_student_home then my navigation drawer view does not work. How can I use the acitivity_student_home layout as setContentView?
activity_student_home layout:
<?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"
android:background="#drawable/app_back"
tools:context="bd.edu.bubt.regup.StudentHomeActivity">
<LinearLayout
android:layout_centerHorizontal="true"
android:layout_centerVertical="false"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="60dp"
android:id="#+id/linearLayout">
<TextView
android:id="#+id/showtext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:gravity="center"
android:text="Demo"
android:textSize="24dp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
activity_student_home2 layout:
<?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_student_home"
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_student_home"
app:menu="#menu/activity_student_home2_drawer" />
</android.support.v4.widget.DrawerLayout>
app_bar_student_home layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:background="#drawable/app_back"
tools:context="bd.edu.bubt.regup.StudentHomeActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_student_home" />
</android.support.design.widget.CoordinatorLayout>
StudentHomeActivity java class:
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class StudentHomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
String name, id, dept, intake, sec, mail;
TextView showtext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_home2);
showtext = (TextView) findViewById(R.id.showtext); //content of activity_student_home
showtext.setText("Registration is open"); //does not work. Null pointer exception.
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.addDrawerListener(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.menu_bvault) {
// Handle the camera action
} else if (id == R.id.menu_account) {
} else if (id == R.id.menu_pass_change) {
} else if (id == R.id.menu_logout) {
} else if (id == R.id.menu_about) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Your activity_student_home does not include your DrawerLayout
This is missing
<include
layout="#layout/app_bar_student_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
The correct way to do what you wish is (if I understand what you are asking for correctly) to use fragments
Inside your app_bar_student_home.xml replace
<include layout="#layout/content_student_home" />
with something like this
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_height="match_parent"/>
Then create fragments whose content you wish to show (let's say FragmentA, FragmentB) and set their contentview to the different layouts you wish to show
when you wish to change the content for your activity you can do something like
getSupportFragmentManager().beginTransaction().replace(R.id.content, new FragmentA()).commit();
there's a lot more to it than this,
for example when you wish to send a click event from the fragment to your activity you have to use getActivity() and cast it to the class of your MainActivity or use an interface (preferable)
you can check out this tutorial which should help you
http://www.androiddocs.com/training/basics/fragments/index.html

How to make a fixed BottomNavigationView with title below, no shifted navigation

I am having difficulties in making fixed BottomNavigationView like in the Photo below: OriginalPhoto.png
Here is my own project's BottomNavigationView: MyPhoto.png
Also, I want the title below icons visible all the time, not just when clicked. How can I do this??
Note: I have read all stackoverflow articles and followed other external links but no tangible results have gained. Please help me to figure this subtle problem out. Would be better if only with XML to solve this problem, rather than java code.
Here is my source code for activity_menu.xml, btw, it is not activity_main.xml because i have used main activity for my login page. This activity is after login page: `
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="datasite.com.konnex.Menu"
android:background="#ffffff">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#3fc0ea">
<ImageButton
android:layout_width="120dp"
android:layout_height="38dp"
android:background="#drawable/lg1"
android:layout_marginLeft="130dp"
android:layout_marginStart="130dp"/>
<android.support.v7.widget.SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="90dp"
android:layout_marginStart="90dp"/>
</android.support.v7.widget.Toolbar>
<RelativeLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="2">
<FrameLayout
android:layout_width="191dp"
android:layout_height="150dp"
android:id="#+id/fm_cases"
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground">
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:src="#drawable/cases"
android:layout_marginLeft="50dp"
android:layout_marginStart="50dp"
android:layout_marginTop="35dp"
android:id="#+id/img_cases" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cases"
android:layout_marginLeft="70dp"
android:layout_marginStart="70dp"
android:layout_marginTop="128dp"
android:textSize="18sp"
android:textColor="#424242"/>
<TextView
android:layout_width="22dp"
android:layout_height="wrap_content"
android:text="#string/string_1"
android:textColor="#FFFFFF"
android:textSize="17sp"
android:layout_marginLeft="122dp"
android:layout_marginStart="122dp"
android:layout_marginTop="35dp"
android:background="#E91E63"
android:id="#+id/notif_cases"/>
</FrameLayout>
</GridLayout>
</RelativeLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fffafa"
app:menu="#menu/navigation"
app:itemIconTint="#color/dark"
app:itemTextColor="#color/dark"
android:animateLayoutChanges="false"
android:splitMotionEvents="false"
android:fitsSystemWindows="true"/>
</LinearLayout>`
Here is the source code for menu.java. it is also after main.java activity which is for login used.
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
public class Menu extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_about:
return true;
case R.id.nav_location:
return true;
case R.id.nav_phone:
return true;
case R.id.nav_home:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
FrameLayout fml = (FrameLayout) findViewById(R.id.fm_cases);
fml.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Menu.this, Cases.class);
startActivity(i);
}
});
}
}
Thank you in advance!!! I really need your help Guys)
My Navigation.xml:
`<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/nav_about"
android:icon="#drawable/ic_dashboard_black_24dp"
android:title="#string/title_about" />
<item
android:id="#+id/nav_location"
android:icon="#drawable/nav_location"
android:title="#string/title_location"
/>
<item
android:id="#+id/nav_phone"
android:icon="#drawable/nav_call"
android:title="#string/title_phone"
/>
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/title_home"
/>
</menu>
Try using AHBottomNavigation library, I suggest this because is has simple implementation considering your case and reduces your work to create another menu.xml file and handling menu option methods in your code. Just add this line in your gradle file.
compile 'com.aurelhubert:ahbottomnavigation:2.0.6'
It will take care of the layout issue you have moreover, it has lots of customization options. You can read further here, but for your case the simple use to keep titles is..
public class MyActivity extends AppCompatActivity{
#BindView(R.id.bottom_navigationbar)
AHBottomNavigation bottomNavigation;
onCreate(){
bottomNavigation.addItem(new AHBottomNavigationItem("Title1", iconID1);
bottomNavigation.addItem(new AHBottomNavigationItem("Title2", iconID2);
bottomNavigation.addItem(new AHBottomNavigationItem("Title3", iconID3);
bottomNavigation.addItem(new AHBottomNavigationItem("Title4", iconID4);
bottomNavigation.setAccentColor(ContextCompat.getColor(this, themeColor));
//will always show titles
bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
}}
setUpClickListener.
bottomNavigation.setOnTabSelectedListener((position, wasSelected) -> {
if (position == 0 && !wasSelected) {
} else if (position == 1 && !wasSelected) {
} else if (position == 2 && !wasSelected) {
} else if (position == 3 && !wasSelected) {
} else if (position == 4 && !wasSelected) {
}
return true;
}
);
Ok then try to add app:showAsAction in menu item
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/nav_about"
android:icon="#drawable/ic_dashboard_black_24dp"
app:showAsAction="ifRoom"
android:title="#string/title_about" />
<item
android:id="#+id/nav_location"
android:icon="#drawable/nav_location"
app:showAsAction="ifRoom"
android:title="#string/title_location"
/>
<item
android:id="#+id/nav_phone"
android:icon="#drawable/nav_call"
app:showAsAction="ifRoom"
android:title="#string/title_phone"
/>
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home_black_24dp"
app:showAsAction="ifRoom"
android:title="#string/title_home"
/>
</menu>
If your problem not resolve then replace this one showAsAction="always|withText"
after then you can use this method for disabling shifted menu
public static void disableShiftMode(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
//noinspection RestrictedApi
item.setShiftingMode(false);
// set once again checked value, so view will be updated
//noinspection RestrictedApi
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException e) {
Log.e("BNVHelper", "Unable to get shift mode field", e);
} catch (IllegalAccessException e) {
Log.e("BNVHelper", "Unable to change value of shift mode", e);
}
}
Updated Menu.java: `package datasite.com.konnex;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import java.lang.reflect.Field;
public class Menu extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_about:
return true;
case R.id.nav_location:
return true;
case R.id.nav_phone:
return true;
case R.id.nav_home:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
//Add This
disableShiftMode((BottomNavigationView)findViewById(R.id.navigation))
FrameLayout fml = (FrameLayout) findViewById(R.id.fm_cases);
fml.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Menu.this, Cases.class);
startActivity(i);
}
});
}
public static void disableShiftMode(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
//noinspection RestrictedApi
item.setShiftingMode(false);
// set once again checked value, so view will be updated
//noinspection RestrictedApi
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException e) {
Log.e("BNVHelper", "Unable to get shift mode field", e);
} catch (IllegalAccessException e) {
Log.e("BNVHelper", "Unable to change value of shift mode", e);
}
}
}
Updated Navigation.xml:
`<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/nav_about"
android:icon="#drawable/ic_dashboard_black_24dp"
android:title="#string/title_about"
app:showAsAction="always|withText"/>
<item
android:id="#+id/nav_location"
android:icon="#drawable/nav_location"
android:title="#string/title_location"
app:showAsAction="always|withText" />
<item
android:id="#+id/nav_phone"
android:icon="#drawable/nav_call"
android:title="#string/title_phone"
app:showAsAction="always|withText"/>
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/title_home"
app:showAsAction="always|withText" />
</menu>
`

Missing Hamburger Icon Android

I tried searching for different answers regarding the hamburger icon, but haven't found anything similar. I'm trying to create a hamburger icon and have been following a tutorial. The code runs fine, but the icon is missing when I open it in the virtual device. Any suggestions are appreciated.
activity_main xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.android.navigationapp.navigationapp.MainActivity"
android:id="#+id/drawerLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Main Layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_gravity="center_vertical"
android:textAlignment="center"
android:textSize="24dp" />
</LinearLayout>
<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>
MainActivity Java
package com.android.navigationapp.navigationapp;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Android setting custom actionbar

In my project i would to set a custom actionBar (with a custom layout) after a specific action.
I have this simple Activity:
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity2 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
//apriImpostazioni ();
return true;
case R.id.information_item:
//apriInformazioni ();
return true;
case R.id.search_item:
apriBarraRicerca ();
System.out.println ("IL BOTTONE RICERCA E' PREMUTO");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void apriBarraRicerca () {
getActionBar ().setCustomView(getLayoutInflater().inflate(R.layout.search_layout, null));
}
}
Where "menu_main_activity2" is this xml:
<menu 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"
tools:context="zipangulu.myapplication.MainActivity2">
<item android:id="#+id/action_settings" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
<item android:id="#+id/information_item"
android:title="Info"
android:icon="#drawable/info"
android:orderInCategory="100"
app:showAsAction="always"/>
<item android:id="#+id/search_item"
android:title="Search"
android:icon="#drawable/search_icon"
android:orderInCategory="100"
app:showAsAction="always"/>
</menu>
I would, pressing the search_item on the main actionbar, set a custom actionBar whith this layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:background="#4584d3">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/back_button"
android:background="#null"
android:src="#drawable/back_icon"/>
<AutoCompleteTextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="6"
android:id="#+id/campo_ricerca"/>
<Spinner
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:spinnerMode="dropdown"
android:id="#+id/spinner_anno"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/search_icon"
android:id="#+id/avvia_ricerca"/>
</LinearLayout>
But at runtime I have a NullPointerException in the body of "apriBarraRicerca" method..why?How can I fix this problem?
EDIT: as suggested I replaced "getActionBar ()" with "getSupportActionBar ()", now I don't have any exception but nothing happens.
EDIT2: I added getSupportActionBar().setDisplayShowCustomEnabled(true); and now my custom actionbar is visible but not as i want, look at the following image:
http://bit.ly/1Dc2kGg
The bar is visible but cutted, and are visible also the items of the previous actionBar..
You can try do the same thing with the android.support.v7.widget.ToolBar
Your Layout which you can populate as you desire:
<?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:background="#688A08"
android:layout_height="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>
You have to modify the values->styles.xml:
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
</resources>
And the in the onCreate() method you do the following:
Toolbar tb = (Toolbar)findViewById(R.id.top_bar);
if(tb != null){
setSupportActionBar(tb);
}
Hope it helps!!!

Categories