I'm trying to get the navigation drawer down, i've followed a few tutorials around the internet however they all end up not working. Now I know it's something simple but I can't figure it out. Menu opens, main fragment loads, but if I click a new fragment, nothing works. ideas?
activity_main.xml
<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_main_drawer" />
MainFragment java
package com.autotools.autotools;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainFragment extends Fragment {
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Inflate the layout for this fragment
return rootView;
}
}
Second Fragment
package com.autotools.autotools;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class autoLoanFragment extends Fragment {
public autoLoanFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_autoloan,container,false);
}
}
MainActivity java
package com.autotools.autotools;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
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 com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
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);
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);
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();
}
#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_home) {
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_autoLoan) {
autoLoanFragment fragment = new autoLoanFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gas) {
} else if (id == R.id.nav_settings) {
} 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;
}
}
Fragment_main xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal|top" />
</FrameLayout>
activity_main_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_home"
android:icon="#drawable/ic_info_black_48dp"
android:title="Home" />
<item
android:id="#+id/nav_autoLoan"
android:icon="#drawable/ic_attach_money_black_48dp"
android:title="Auto Loan Calculator" />
<item
android:id="#+id/nav_gas"
android:icon="#drawable/ic_local_gas_station_black_48dp"
android:title="Slideshow" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_settings_black_48dp"
android:title="Settings" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="Share" />
<item
android:id="#+id/nav_send"
android:icon="#drawable/ic_menu_send"
android:title="Send" />
</menu>
</item>
</menu>
Related
I am trying to figure out where I should be putting the nav_host in my xml files. I am not fully understanding how to get around my application fragments in general.
I have read this Add Drawer layout into main activity
I had most of this working before trying to add the Navigation host (Meaning I could use the drawer menu and navigate). I have not been able to navigate from a fragment to anywhere else with a button that is on that fragment.
My current activity_main.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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<androidx.fragment.app.FragmentContainerView
android:id="#+id/mainActivityHost"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation"
tools:layout="#layout/fragment_home" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/drawer_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
Is where I have the nav_host correct? Or should I have a different Fragment all together for the nav_host?
My MainActivity.class
package com.signin.app;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
// The program should always start on home.
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.mainActivityHost, new HomeFragment()).commit();
navigationView.setCheckedItem(R.id.nav_home);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
} else if (id == R.id.nav_signin) {
} else if (id == R.id.nav_flights) {
} else if (id == R.id.nav_hotels) {
} else if (id == R.id.nav_profile) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//
// #Override
// public void onBackPressed() {
// if (drawer.isDrawerOpen(GravityCompat.START)) {
// drawer.closeDrawer(GravityCompat.START);
// } else {
// super.onBackPressed();
// }
// }
}
Before I messed with it I could open the drawer click the menu items and go to a fragment, so pretending that still worked the problem was that I could go to Signin fragment, but the buttons on that fragment would not take me anywhere, they mostly just crashed the application.
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
public class SigninFragment extends Fragment {
private EditText editText;
private Button btn_signup, btn_signin, btn_forgot_pass;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container,false);
editText = view.findViewById(R.id.email);
btn_signup = view.findViewById(R.id.btn_signup);
btn_signin = view.findViewById(R.id.btn_signin);
btn_forgot_pass = view.findViewById(R.id.btn_forgot_pass);
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(getContext(), "Sign Up", Toast.LENGTH_SHORT).show();
Navigation.findNavController(view).navigate(R.id.nav_signup);
}
});
btn_signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Sign in", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}```
Also, please note that nav_signup is not in the drawer menu so I wasn't sure where I was supposed to identify it, (i.e., in the fragment_signup.xml, in its own menu, somewhere else.) right now the id for fragment_signup, is `android:id="#+id/nav_signup"`
I'm not sure I understand the question
Navigation.findNavController(view).navigate(R.id.nav_signup); - it should do the navigation and R.id.nav_signup should be destination or action. I'm not sure what R.id.nav_signup is atm. If destination then probably it should be fragment id.
Here's doc about navigations https://developer.android.com/guide/navigation/navigation-navigate#java
And here is Google course about navigation between fragments https://developer.android.com/codelabs/basic-android-kotlin-training-fragments-navigation-component#6 (This guide is in Kotlin but that's just a syntax difference, hopefully still can be useful)
And the final code of this is here https://github.com/google-developer-training/android-basics-kotlin-words-app (it uses navigation/nav_graph.xml to define navigations between fragments)
And for example in src/main/java/com/example/wordsapp/LetterAdapter.kt has navigation to different fragment.
holder.button.setOnClickListener {
// LetterListFragmentDirections is defined in nav_graph.xml
val action = LetterListFragmentDirections.actionLetterListFragmentToWordListFragment(letter = holder.button.text.toString())
// Navigate using that action
holder.view.findNavController().navigate(action)
}
I haven't used fragments a long time, but I hope this will be helpful :)
I am new with Android development, so this is probably a rookie mistake but, I am stuck.
I want to start an activity when clicking on the menu, but the following exception shows up:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.mygymroutine.mygymroutine/com.mygymroutine.mygymroutine.activities.ActivitySchedule}:
java.lang.IllegalArgumentException: No view found for id 0x7f0d008b
(com.mygymroutine.mygymroutine:id/fragment_schedule) for fragment
ScheduleFragment{39f1839 #0 id=0x7f0d008b ...
This is the code related:
public class basic extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic);
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);
displaySelectedScreen(R.id.nav_schedule);
}
#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.basic, 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);
}
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
Intent intent=null;
switch (itemId) {
case R.id.nav_schedule:
intent=new Intent(this, ActivitySchedule.class);
startActivity(intent);
break;
}
Activity code
package com.mygymroutine.mygymroutine.activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.mygymroutine.mygymroutine.Fragments.ScheduleFragment;
import com.mygymroutine.mygymroutine.R;
public class ActivitySchedule extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acivity_schedule);
if(savedInstanceState==null){
ScheduleFragment fg = new ScheduleFragment();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_schedule, fg)
.commit();
}
}
}
Fragment
package com.mygymroutine.mygymroutine.Fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mygymroutine.mygymroutine.R;
public class ScheduleFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
View rootView=inflater.inflate(R.layout.fragment_schedule, container, false);
FloatingActionButton fab=(FloatingActionButton)rootView.findViewById(R.id.fab_schedule);
return inflater.inflate(R.layout.fragment_schedule, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Schedule");
}
}
Fragment Schedule xml
<?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"
android:id="#+id/fragment_schedule"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Schedule"
android:textAppearance="?android:attr/textAppearanceLarge" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_schedule"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="41dp"
android:layout_marginEnd="32dp"
android:layout_marginRight="32dp"
android:clickable="true"
android:tint="#android:color/background_light"
app:backgroundTint="#android:color/holo_red_light"
app:fabSize="mini"
app:rippleColor="#android:color/transparent"
app:srcCompat="#android:drawable/ic_menu_add" />
</RelativeLayout>
Activity schedule xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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.mygymroutine.mygymroutine.activities.ActivitySchedule">
</android.support.constraint.ConstraintLayout>
Here:
getSupportFragmentManager().beginTransaction().add(R.id.fragment_schedule, fg)
.commit();
You are passing R.id.fragment_schedule as the container of the fragment. Where the fragment will be inserted. However, R.id.fragment_schedule is part of your Fragment. So, it was not inflated yet. You can't use it as container since it was not created yet.
I think you want is:
<android.support.constraint.ConstraintLayout 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.mygymroutine.mygymroutine.activities.ActivitySchedule"
<!-- ADD LINE BELOW -->
android:id="#+id/fragment_container" >
</android.support.constraint.ConstraintLayout>
And change this:
getSupportFragmentManager().beginTransaction().add(R.id.fragment_schedule, fg)
.commit();
to this:
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, fg)
.commit();
In. The onOptionsItemSelected method add the following
(This method brings a parameter - MenuItem item)
switch (item.getItemId())
case R.id.myFirst
startActivity(new Intent(this, MyFirstActivity.class));
case R.id.mySecond
startActivity (newIntent(this, MySecondActivity.class));
And so on. You may define a layout for the activity with necessary views. You may also declare the activity in the Manifest file.
This works. I am starting my activities from the main like this.
I have created a navigation drawer in my AbstractActivity.class and i want to use that drawer in all my activities , so i created another drawer class and extending that class in another activity but it isnt working , can anyonetell me whats wrong in my code ?
Abstractactivity.class
package com.astro.famouspandit.Activities.Abstract;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Image;
import android.os.Bundle;
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.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.astro.famouspandit.Activities.Activity.ChartStyle;
import com.astro.famouspandit.Activities.Activity.Contact;
import com.astro.famouspandit.Activities.Activity.Settings;
import com.astro.famouspandit.Activities.Activity.Welcome;
import com.astro.famouspandit.R;
public class AbstractActivity extends AppCompatActivity {
private String[] mPlanetTitles;
private LinearLayout mDrawerList;
protected DrawerLayout mDrawerLayout;
protected ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
protected Toolbar toolbar;
protected FrameLayout framelayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_abstract);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (LinearLayout) findViewById(R.id.left_drawer);
framelayout = (FrameLayout)findViewById(R.id.content_frame);
mTitle = mDrawerTitle = getTitle().toString();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
toolbar, R.string.drawer_open, R.string.drawer_close){
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_Aboutus).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void selectItem(int position) {
switch(position) {
case 1:
Intent a = new Intent(this, Welcome.class);
startActivity(a);
break;
case 2:
Intent b = new Intent(this, Welcome.class);
startActivity(b);
break;
default:
}
}
public boolean onOptionsItemSelected(MenuItem item){
int items = item.getItemId();
switch(items){
case R.id.action_Settings:{
Intent intent = new Intent(this,Settings.class);
startActivity(intent);
}break;
case R.id.action_Contact_us:{
Intent intent = new Intent(this,Contact.class);
startActivity(intent);
}break;
case R.id.action_Aboutus:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
case R.id.action_Profile:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
}
return super.onOptionsItemSelected(item);
}
}
activity_abstract.xml
<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">
<include layout="#layout/toolbar"/>
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<LinearLayout android:id="#+id/left_drawer"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#0F6177">
<LinearLayout android:id="#+id/view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="#layout/navigation_drawer"></include>
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
NavigationActivity.class
package com.astro.famouspandit.Activities.Abstract;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.astro.famouspandit.R;
public abstract class NavigationActivity extends AppCompatActivity implements View.OnClickListener{
protected DrawerLayout mDrawerLayout;
private LinearLayout mFrameLayout_HeaderView;
protected FrameLayout mFrameLayout_ContentFrame;
protected ActionBarDrawerToggle mActionBarDrawerToggle;
protected Toolbar mToolbar;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mFrameLayout_ContentFrame = (FrameLayout) findViewById(R.id.main_activity_content_frame);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mFrameLayout_HeaderView = (LinearLayout) findViewById(R.id.mainLayout);
mFrameLayout_HeaderView.setOnClickListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.main_activity_DrawerLayout);
mDrawerLayout.closeDrawers();
mDrawerLayout.setStatusBarBackground(R.color.colorPrimary);
mActionBarDrawerToggle = new ActionBarDrawerToggle
(
this,
mDrawerLayout,
mToolbar,
R.string.drawer_open,
R.string.drawer_close
) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Disables the burger/arrow animation by default
super.onDrawerSlide(drawerView, 0);
}
};
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
mActionBarDrawerToggle.syncState();
}
}
activity_navigationactivity.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_activity_DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- The main content view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/main_activity_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer -->
<include layout="#layout/navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
class where i am extending NavigationActivity Class
public class Welcome extends NavigationActivity implements View.OnClickListener{
private CardView mAstro,mMatch,mPanch,mAsk,mContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_welcome,mFrameLayout_ContentFrame);
This is a fairly common question has been blogged about. Essentially, you want to create a BaseActivity with a layout that contains the Navigation Drawer and then have your other Activities extend the BaseActivity and inflate their layouts within the BaseActivity's layout. This way you have the Navigation Drawer in all your activity and reuse the code for setting up the Drawer (since that code lives in the BaseActivity).
You can find an example implementation along with a more detailed explanation here: http://lucas-dev.com/blog/entry/base-activities-sliding-menu.html
I have an android app with a Navigation Drawer, which should change between fragments. But my main fragment (the only fragment now) doesn't show up. It is just an empty screen. Could someone tell me what did I do wrong?
Thanks in advance.
MainActivity.java:
package com.asd.apptest;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
homescreen home_fragment = new homescreen();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFragments();
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);
navigationView.getMenu().getItem(0).setChecked(true);
}
#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) {
int id = item.getItemId();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (id == R.id.nav_home) {
ft.show(home_fragment);
ft.commit();
} else if (id == R.id.nav_light) {
} else if (id == R.id.nav_add_device) {
} else if (id == R.id.nav_settings_app) {
} else if (id == R.id.nav_settings_server) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void initFragments() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_container, home_fragment);
//ft.hide(mGalleryFragment);
ft.commit();
}
}
app_bar_main.xml:
<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>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
homescreen.java:
package com.asd.apptest;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class homescreen extends Fragment {
public homescreen (){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_homescreen, container, false);
return rootView;
}
}
fragment_homescreen.xml only contains a textview and show up properly n the editor.
I have a Problem with switching Fragments in the default Navigation Drawer
MainActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.app.Fragment;
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.view.View;
package flo.nawigator;
#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, "HILFE:" +
" An der oberen linken Ecke, findest Du Drei Striche mit dem sich ein Menü öffnen lässt", 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();
Fragment fragment;
if (id == R.id.nav_gallery) {
} else if (id == R.id.Experimente) {
} else if (id == R.id.nav_formeln) {
} 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;
}
}
ContentMain.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView android:text="#string/TextViewIntro" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elegantTextHeight="false"
android:gravity="top|center"
android:textColor="#000000"
android:textSize="#dimen/abc_text_size_title_material"
android:id="#+id/TextViewIntro"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fab"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="53dp"
android:src="#android:drawable/ic_menu_help" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignTop="#+id/TextViewIntro"
android:layout_alignParentEnd="true"
android:id="#+id/mainFrame"></FrameLayout>
BlankFragment.java
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
package flo.nawigator;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fraglayoutv = inflater.inflate(R.layout.fragment_blank, null);
fragbtn1 = (Button) fraglayoutv.findViewById(R.id.buttonfrag1);
fragbtn1.setOnClickListener(this);
return fraglayoutv;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonfrag1: {
Toast.makeText(getActivity(), "Button gedrückt!!", Toast.LENGTH_SHORT).show();
}
}
}
I have a BlankFragment! How do I Switch to it with Android Navigation Drawer
MainActivity.xml
<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_main_drawer" />
fragment_blank.xml
<RelativeLayout 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="flo.nawigator.BlankFragment"
android:id="#+id/fragmentgalerie">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/galeriefragtext"
android:id="#+id/textView"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Okay!"
android:id="#+id/buttonfrag1"
android:layout_alignParentBottom="true"
android:layout_alignStart="#+id/textView"
android:layout_marginBottom="217dp" />
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment;
if (id == R.id.nav_gallery) {
} else if (id == R.id.Experimente) {
BlankFragment bnlfrgmnt = new BlankFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.mainFrame, bnlfrgmnt).commit();
//do similar for other navigation drawer items to display other fragments.
} else if (id == R.id.nav_formeln) {
} 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;
}