Navigation menu not working in Child Activity - java

so i made a menu class and now i try to extend my others activitys from that one
i get the button but the slide its not working in the others activitys but its apears on the left top... lest go to the code
this is my xml activity_navigatoin_menu
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
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="ar.com.puebloyreforma.pyr.NavigationMenu">
<android.support.design.widget.NavigationView
app:headerLayout="#layout/menuheader"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/caldroid_black"
app:itemTextColor="#color/white"
app:itemIconTint="#color/white"
app:menu="#menu/drawermenu"
android:layout_gravity="start"
>
</android.support.design.widget.NavigationView>
this is my menudrawer
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/noticias" android:title="Noticias" android:icon="#drawable/iconews"></item>
<item android:id="#+id/calendario" android:title="Calendario" android:icon="#drawable/icocalen"></item>
<item android:id="#+id/sysacad" android:title="Sysacad" android:icon="#drawable/icosysa"></item>
<item android:id="#+id/contacto" android:title="Contacto" android:icon="#drawable/icocon"></item>
<item android:id="#+id/reglamento" android:title="Reglamento" android:icon="#drawable/icoreg"></item>
</menu>
and here my activity
package ar.com.puebloyreforma.pyr;
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 NavigationMenu extends AppCompatActivity {
private DrawerLayout mDL ;
private ActionBarDrawerToggle mT ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_menu);
mDL = (DrawerLayout) findViewById(R.id.drawer) ;
mT = new ActionBarDrawerToggle(this , mDL ,R.string.open , R.string.close) ;
mDL.addDrawerListener(mT);
mT.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mT.onOptionsItemSelected(item)){
return true ;
}
return super.onOptionsItemSelected(item);
}
}
and this is one child activity
package ar.com.puebloyreforma.pyr;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
public class PdfsActivity extends NavigationMenu {
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String target ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdfs);
Button tt , tm , tn, reg ;
tt = (Button)this.findViewById(R.id.tt);
tm = (Button)this.findViewById(R.id.tm);
tn = (Button)this.findViewById(R.id.tn);
reg = (Button)this.findViewById(R.id.reg);
final String pdfs[] = {"tm" ,
"tt" ,
"tn",
"Ord1549"
} ;
tm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setTarget(pdfs[0]);
Intent hola = new Intent (PdfsActivity.this,ReglamentoActivity.class);
hola.putExtra("TARGET", getTarget());
startActivity(hola);
}
});
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setTarget(pdfs[1]);
Intent hola = new Intent (PdfsActivity.this,ReglamentoActivity.class);
hola.putExtra("TARGET", getTarget());
startActivity(hola);
}
});
tn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setTarget(pdfs[2]);
Intent hola = new Intent (PdfsActivity.this,ReglamentoActivity.class);
hola.putExtra("TARGET", getTarget());
startActivity(hola);
}
});
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setTarget(pdfs[3]);
Intent hola = new Intent (PdfsActivity.this,ReglamentoActivity.class);
hola.putExtra("TARGET", getTarget());
startActivity(hola);
}
});
}
that has its onw layout
<?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"
android:orientation="vertical"
tools:context="ar.com.puebloyreforma.pyr.PdfsActivity">
<Button
android:id="#+id/tm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MAñANA"
android:layout_marginRight="60dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintVertical_bias="0.758"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent" />
<Button
android:id="#+id/tt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TARDE"
android:layout_marginBottom="8dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintVertical_bias="0.335"
android:layout_marginRight="123dp"
app:layout_constraintRight_toRightOf="parent" />
<Button
android:id="#+id/tn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NOCHE"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
android:layout_marginLeft="68dp"
app:layout_constraintVertical_bias="0.572"
app:layout_constraintLeft_toLeftOf="parent" />
<Button
android:id="#+id/reg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="REGLA"
app:layout_constraintLeft_toRightOf="#+id/tn"
android:layout_marginLeft="0dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
android:layout_marginRight="8dp"
app:layout_constraintVertical_bias="0.572"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.713" />
</android.support.constraint.ConstraintLayout>

Let me post my code with which I manage to obtain NavigationDrawer in child activity.
MyAppCompatActivity(ParentActivity class)
public abstract class MyAppCompatActivity extends BaseAppCompatActivity {
#Override
public void setContentView(#LayoutRes int layoutResID) {
CoordinatorLayout activityParentBase = (CoordinatorLayout) getLayoutInflater().inflate(R.layout.activity_navigation_drawer, null);
RelativeLayout content = (RelativeLayout) activityParentBase.findViewById(R.id.content);
setContentView(activityParentBase);
getLayoutInflater().inflate(layoutResID, content, true);
super.setContentView(activityParentBase);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
MyAppCompatActivity.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(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_item1) {
} else if (id == R.id.nav_item2) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
}
activity_navigation_drawer.xml(ParentActivity XML)
<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:fitsSystemWindows="true"
tools:context=".MyAppCompatActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
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>
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:openDrawer="start">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content" />
<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:menu="#menu/menu_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</android.support.design.widget.CoordinatorLayout>
ChildNavigationActivity (ChildActivity class)
public class ChildNavigationActivity extends MyAppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child_navigation);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); //we have included "toolbar" in the parentactivity xml. So not need to do it in childactivity xml.
/**NOTE: Do Not use "setSupportActionBar(toolbar)" since you have already done it in your parent activity*/
toolbar.setTitle("ChildNavigationActivity");
}
}
activity_child_navigation(ChildActivity XML)
<FrameLayout 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=".ChildNavigationActivity">
<!--Put all your ChildActivity Widgets here-->
</FrameLayout>

Related

Android Navigation View Item clicks only once

i am having a serious weird bug in android navigation view item click, the items are only clicking once when you open the app and stops clicking after, but the weirdest part is that the item is responding to click at the edge every time.
Below is my main xml code
<?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:layoutDirection="ltr"
tools:openDrawer="start">
<include layout="#layout/layout_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:theme="#style/NavigationView"
app:itemTextColor="#color/black"
app:itemIconTint="#color/black"
android:background="#color/white"
app:headerLayout="#layout/nav_header_main"
android:elevation="5dp"
app:menu="#menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
Navigation menu items
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:checked="true"
android:id="#+id/home"
android:icon="#drawable/ic_home"
android:title="#string/home" />
<item
android:id="#+id/latest"
android:icon="#drawable/ic_latest"
android:title="#string/latest" />
<item
android:id="#+id/category"
android:icon="#drawable/ic_category"
android:title="#string/category" />
</group>
</menu>
The layout Frame
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/toolbar"
android:theme="#style/AppTheme.AppBarOverlay"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:layout_marginTop="55dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frame_one"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
My Activity code
package com.education.books.MySchoolLibrary;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
public class NewAct extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public Toolbar toolbar;
private ProgressBar progressBar;
private DrawerLayout drawer;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Tool");
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();
this.navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerview = navigationView.getHeaderView(0);
findViewById(R.id.frame_one).setOnClickListener(v -> {
Toast.makeText(this, "frame ti ya werey!!!", Toast.LENGTH_SHORT).show();
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
drawer.closeDrawers();
if (id == R.id.home) {
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show();
} else if (id == R.id.latest) {
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show();
} else if (id == R.id.category) {
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show();
}
return true;
}
}
But if i copy this whole code into an entirely new application, it is working fine, pls i don't know what i am doing wrong. Thanks.
I am also facing same issue.found a work around solution like below
nav_view.menu.findItem(R.id.menu_share).setOnMenuItemClickListener {
shareApp()
drawer_layout.closeDrawer(GravityCompat.START)
true
}

OnClickListener Null Object Reference

I know this issue has been put out there 100 times, but nothing I've seen solves this. I have a button in a layout called fragment_main which is shown to another layout: activity_main. That button opens a fragment called AddEditFragment, which allows users to add info to a form that then spits it into a recyclerview(fragment_main) that is shown in MainActivity.
I have both layouts due to having a navigation drawer in a linearlayout in activity_main and the recyclerview and button in fragment_main constraintlayout. However I have onDelete/Edit/Save methods already up and going in MainActivity, so it only makes sense to me to put the button onClickListener there as well. Except since the button isn't in the main layout, activity_main, I get a fatal null object exception.
Even though fragment_main is shown in activity_main is there a way around this so the OnClick method can be put into MainActivity for a button in a linked layout?
MainActivity.java
public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.OnVehicleClickListener,
FragmentAddEdit.OnSaveClicked,
NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// Launcher view
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentMainActivity()).commit();
navigationView.setCheckedItem(R.id.nav_garage);
}
Button button_add = findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddEditRequest(null);
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_garage:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentMainActivity()).commit();
break;
case R.id.nav_history:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentHistory()).commit();
break;
case R.id.nav_upcoming:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentUpcoming()).commit();
break;
case R.id.nav_about:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentAbout()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onSaveClicked() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment AddEditFragment = fragmentManager.findFragmentById(R.id.fragment_container);
if (AddEditFragment != null) {
getSupportFragmentManager().beginTransaction()
.remove(AddEditFragment)
.commit();
}
}
public void onEditClick(#NonNull Vehicle vehicle) {
AddEditRequest(vehicle);
}
#Override
public void onDeleteClick(#NonNull Vehicle vehicle) {
}
private void AddEditRequest(Vehicle vehicle) {
Intent detailIntent = new Intent(this, FragmentAddEdit.class);
if (vehicle != null) {
detailIntent.putExtra(Vehicle.class.getSimpleName(), vehicle);
startActivity(detailIntent);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
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: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=".com.carupkeep.MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.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"
app:menu="#menu/drawer_menu" />
</android.support.v4.widget.DrawerLayout>
fragment_main.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:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".com.carupkeep.FragmentMainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/no_vehicles"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/no_vehicle_message"
android:textSize="22sp"
android:textStyle="normal|bold"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1"/>
<Button
android:id="#+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:drawableLeft="#drawable/ic_add"
android:drawablePadding="10dp"
android:drawableTint="#color/colorAdd"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="#string/addVehicle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/vehicle_list" />
<android.support.v7.widget.RecyclerView
android:id="#+id/vehicle_list"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/no_vehicles"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>
UPDATE
I got close but still feel so far. I've given up on trying to keep it in MainActivity and put it in FragmentMainAcitivity as suggested. Except now I have 2 can't resolve errors. The first being on view in view.findViewById button initialization AND on fragment_container in the callback method. Any thoughts on how to resolve this?
public class FragmentMainActivity extends Fragment {
Button button_add = view.findViewById(R.id.button_add);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
Fragment AddEditFragment = fragmentManager.findFragmentById(R.id.fragment_container);
getFragmentManager().beginTransaction().replace(fragment_container, AddEditFragment).commit();
}
});
}
}
easier way to do it is to put
onClick="AddEditRequestView"
in your fragment_main.xml
so it will be
<Button
android:id="#+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:drawableLeft="#drawable/ic_add"
android:drawablePadding="10dp"
android:drawableTint="#color/colorAdd"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="#string/addVehicle"
android:onClick="AddEditRequestView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/vehicle_list" />
and in your MainActivity.java
add this method
public void AddEditRequestView(View viewc){
AddEditRequest(null);
}
and delete these code from your activity
Button button_add = findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddEditRequest(null);
}
});

One activity with fragments and a navigation drawer

So, I want to build an app that has only one activity and will use multiple fragments. I have a log in activity, and after I make the log in I go to my maintactivity that has a fragment and a view-pager so I can swipe through some fragments(this fragments will be like a day of a calendar). My navigation drawer will be used to open other fragments, no the same as the ones mentioned before. My issues are, after I apply the view-pager, my button to open the drawer doesn't work and my fragments doesn't change when I click in the navigation drawer items, is keeps the fragment on top (I open it with the slide movement, since the button doesn't work). Here is my code:
MainActivity.java
package amsi.dei.estg.ipleiria.pt.projeto;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
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.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final int NUM_PAGES = 5;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
setSupportActionBar(toolbar);
final 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();
}
}
//since I have two onBackPressed, on for the drawer and other for my pageview, I left the one I thought would be more useful.
/*#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new Dia();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
public boolean onNavigationItemSelected(MenuItem item){
int id = item.getItemId();
Fragment fragment = null;
if(id==R.id.nav_dia)
{
fragment = new Dia();
}
else if(id==R.id.nav_meusAlimentos)
{
fragment = new MeusAlimentos();
}
else if(id==R.id.nav_login)
{
Intent login = new Intent(this, LogIn.class);
startActivity(login);
}
if(fragment != null){
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.screen_area, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
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: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_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<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" />
</android.support.v4.widget.DrawerLayout>
content_main.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"
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="amsi.dei.estg.ipleiria.pt.projeto.MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/screen_area"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Dia.java
package amsi.dei.estg.ipleiria.pt.projeto;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by nelsu on 24/11/2017.
*/
public class Dia extends Fragment {
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Day");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootview = (ViewGroup) inflater.inflate(R.layout.activity_dia_content, container, false);
return rootview;
//return inflater.inflate(R.layout.activity_dia_content, null);
}
}
app_bar_main.xml
<?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"
tools:context="amsi.dei.estg.ipleiria.pt.projeto.MainActivity">
<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_main" />
</android.support.design.widget.CoordinatorLayout>
activity_dia_content.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="horizontal"
android:clickable="false"
android:focusable="false">
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/rectangle_dia_macros"
android:orientation="vertical">
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="gráficos e percentagem das macros"
android:textAlignment="center"
android:layout_gravity="center"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView8"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_gravity="center"
android:background="#drawable/rectangle_dia_refeicao"
android:text="Pequeno Almoço" />
<TextView
android:id="#+id/textView7"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_gravity="center"
android:background="#drawable/rectangle_dia_refeicao"
android:text="Café da manhã" />
<TextView
android:id="#+id/textView9"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_gravity="center"
android:background="#drawable/rectangle_dia_refeicao"
android:text="Almoço" />
<TextView
android:id="#+id/textView10"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_gravity="center"
android:background="#drawable/rectangle_dia_refeicao"
android:text="Lanche" />
<TextView
android:id="#+id/textView11"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_gravity="center"
android:background="#drawable/rectangle_dia_refeicao"
android:text="Jantar" />
<TextView
android:id="#+id/textView12"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_gravity="center"
android:background="#drawable/rectangle_dia_refeicao"
android:text="Lanche da noite" />
<Space
android:layout_width="match_parent"
android:layout_height="0dp" />
</LinearLayout>
</LinearLayout>
</ScrollView>
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android: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">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
app:srcCompat="#mipmap/ic_launcher_round" />
<TextView
android:id="#+id/label_nome_user"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_dia"
android:icon="#drawable/ic_menu_camera"
android:title="Dia" />
<item
android:id="#+id/nav_meusAlimentos"
android:icon="#drawable/ic_menu_gallery"
android:title="Meus Alimentos" />
<item
android:id="#+id/nav_login"
android:icon="#drawable/ic_menu_slideshow"
android:title="Login" />
<item
android:id="#+id/nav_manage"
android:icon="#drawable/ic_menu_manage"
android:title="Tools" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_menu_manage"
android:title="Settings" />
<item
android:id="#+id/nav_about"
android:icon="#drawable/ic_menu_manage"
android:title="About" />
<item
android:id="#+id/nav_quit"
android:icon="#drawable/ic_menu_manage"
android:title="Quit" />
</group>
</menu>
You don't have to write your own code for this.
here is a nice library for your problem with all required things.
https://github.com/chrisbanes/cheesesquare

Android Studio have different toolbar items on different activity's

I am very new when it comes to android app development and android studio.
I have been searching around for some couple days but still havent found the solution.
How can i have different toolbar Items on different activity's is their an way to do that ?
Do you have an example so i could take a look at that?
Do you know an tutorial that has that in it?
already much thanks for the help.
MainActivity.java
package com.example.stage.absa;
import android.Manifest;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class MainActivity extends AbsRuntimePermission {
private ZXingScannerView scannerView;
private static final int REQUEST_PERMISSION = 10;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
requestAppPermissions(new String[]{
Manifest.permission.CAMERA},
R.string.msg, REQUEST_PERMISSION);
}
#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, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (id == R.id.action_settings) {
setContentView(R.layout.activity_settings);
return true;
}
return super.onOptionsItemSelected(item);
}
public void browser1(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.suppliance.nl/"));
startActivity(browserIntent);
}
public void scanCode(View view) {
scannerView = new ZXingScannerView(this);
scannerView.setResultHandler(new ZxingScannerResultHandler());
setContentView(scannerView);
scannerView.startCamera();
}
class ZxingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
String resultCode = result.getText();
Toast.makeText(MainActivity.this, resultCode, Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scannerView.stopCamera();
}
}
#Override
public void onPermissionsGranted(int requestCode) {
//Do anything when permisson granted
Toast.makeText(getApplicationContext(), "Toegang geaccepteerd", Toast.LENGTH_LONG).show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:titleTextColor="#android:color/white"
android:background="?attr/colorPrimary">
</android.support.v7.widget.Toolbar>
<!-- Layout for content is here. This can be a RelativeLayout -->
<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"
tools:context="com.example.stage.absa.MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="browser1"
android:layout_margin="2dp"
android:src="#drawable/suppliance" />
<Button
android:id="#+id/S"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="scanCode"
android:layout_margin="5dp"
android:backgroundTint="#color/colorPrimary"
android:text="Scan" />
</RelativeLayout>
</LinearLayout>
SettingsActivity.java
package com.example.stage.absa;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
public class SettingsActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#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_settings, menu);
return true;
}
}
activity_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
app:titleTextColor="#android:color/white"
android:layout_height="?attr/actionBarSize">
<ImageView
android:id="#+id/tv_header_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginRight="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Name"
android:textColor="#ffffff"
android:gravity="center"
android:id="#+id/brand_name" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_marginLeft="5dp"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C Name :"
android:layout_gravity="right"
android:layout_marginRight="20dp"
android:textColor="#ffffff"
android:id="#+id/t1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name :"
android:layout_gravity="right"
android:layout_marginRight="20dp"
android:textColor="#ffffff"
android:id="#+id/t2" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<!-- Layout for content is here. This can be a RelativeLayout -->
<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"
tools:context="com.example.stage.absa.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Settings" />
</RelativeLayout>
</LinearLayout>
menu_settings.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/action_settings"
android:icon="#drawable/ic_action_back"
android:title="Back"
app:showAsAction="ifRoom" />
</menu>
menu_main.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/action_settings"
android:icon="#drawable/ic_action_settings"
android:title="Settings"
app:showAsAction="ifRoom" />
</menu>
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu1, menu);
return true;
}
Just pass different menu resources for the different activities ie R.id.menu1 or R.menu.menu2.
You can set custom toolbar layout for any activity like.
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
app:titleTextColor="#android:color/white"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/AppTheme.PopupOverlay">
<ImageView
android:id="#+id/tv_header_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginRight="20dp"
android:src="#drawable/siyaram_logo"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Name"
android:textColor="#ffffff"
android:gravity="center"
android:id="#+id/brand_name" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_marginLeft="5dp"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C Name :"
android:layout_gravity="right"
android:layout_marginRight="20dp"
android:textColor="#ffffff"
android:id="#+id/t1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name :"
android:layout_gravity="right"
android:layout_marginRight="20dp"
android:textColor="#ffffff"
android:id="#+id/t2" />
</LinearLayout>
</android.support.v7.widget.Toolbar>

ViewPager + TabLayout with NavigationDrawer in every Activity - Issue

I encountered a problem that I didn't managed to solve: I have a MainActivity where there's a NavigationDrawer that allows me to go to three different activities. Those extend the MainActivity so I get the Drawer in every activity.
In the same MainActivity, I put a TabLayout with three tab Fragments.
The problem I'm facing is that whenever I go to one of the three activity from the drawer layout, I don't get the layout xml attached to Activity1 but instead I get again the TabLayout with the Fragments.
How can I solve this?
The result should look like Google Play app.
Here's my MainActivity:
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_layout);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
mTitle.setText(R.string.app_name);
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
this.getSupportActionBar().setDisplayShowTitleEnabled(false);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
Button button1 = (Button)findViewById(R.id.button1); //this is inside the drawer layout
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Activity1.class);
startActivity(intent);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
null,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View v) {
super.onDrawerClosed(v);
invalidateOptionsMenu();
syncState();
}
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
invalidateOptionsMenu();
syncState();
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerToggle.syncState();
mCollectionPagerAdapter = new CollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
TabLayout tabs = (TabLayout)findViewById(R.id.tabs);
tabs.setupWithViewPager(mViewPager);
}
public class CollectionPagerAdapter extends FragmentPagerAdapter {
//final int NUM_ITEMS = 3; // number of tabs
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position) {
case 0:
return new Tab1();
case 1:
return new Tab2();
case 2:
return new Tab3();
}
return null;
}
#Override
public int getCount()
{
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0:
return getString(R.string.tab1);
case 1:
return getString(R.string.tab2);
case 2:
return getString(R.string.tab3);
}
return null;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
Activity1:
public class Activity1 extends MainActivity { //extends MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.classe1); //setContentView before super.onCreate(savedInstanceState) allows me to get drawer in each activity
super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_layout);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
mTitle.setText("Activity 1");
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
this.getSupportActionBar().setDisplayShowTitleEnabled(false);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Tab1 (Fragment):
public class Tab1 extends Fragment {
View view;
public Tab1() {
}
#SuppressLint("InflateParams")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.tab1, null);
return view;
}
and my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent">
<android.support.v4.view.ViewPager
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_marginBottom="60dp"
android:id="#+id/pager">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:overScrollMode="never">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</android.support.v4.view.ViewPager>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/tabs"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/colorPrimaryDark"
app:tabTextColor="#color/tab_text"
app:tabIndicatorColor="#android:color/transparent"
app:tabBackground="#drawable/selected_tab_color"
style="#style/MyCustomTabLayout"/>
<include layout="#layout/toolbar" android:id="#+id/toolbar_layout"/>
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="304dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:clickable="true"
android:background="#ffffff">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/uno"
android:text="Button to Activity1"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
classe1.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<FrameLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_marginBottom="30dp"
android:id="#+id/content_frame">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:overScrollMode="never">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="CLASSE 1"
android:textSize="35sp"
android:gravity="center"/>
</LinearLayout>
</ScrollView>
</FrameLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom">
<include layout="#layout/toolbar" android:id="#+id/toolbar_layout"/>
</RelativeLayout>
</RelativeLayout>
Your problem is that the super.onCreate() call in Activity1 is calling setContentView() again in MainActivity, which is completely replacing Activity1's layout set with its call to setContentView().
Since you want tabs in MainActivity but not the other Activities, your other Activities shouldn't extend MainActivity. Instead, you should create a base Activity with the DrawerLayout that all of your Activities extend, including MainActivity, and then add whichever Views you need in the individual subclasses.
In the base Activity, we'll override the setContentView() method to first set the base layout, setup the drawer and toggle, and then inflate the subclass's layout into the DrawerLayout's content View. Note that we do not call setContentView() in the base Activity's onCreate() method.
public abstract class BaseActivity extends AppCompatActivity {
protected Toolbar toolbar;
protected DrawerLayout mDrawerLayout;
protected ActionBarDrawerToggle mDrawerToggle;
protected TextView mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
#Override
public void setContentView(int layoutResID) {
super.setContentView(R.layout.activity_base);
toolbar = (Toolbar) findViewById(R.id.toolbar_layout);
mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
mTitle.setText(R.string.app_name);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//this is inside the drawer layout
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BaseActivity.this, Activity1.class);
startActivity(intent);
}
});
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
null,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View v) {
super.onDrawerClosed(v);
invalidateOptionsMenu();
syncState();
}
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
invalidateOptionsMenu();
syncState();
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerToggle.syncState();
getLayoutInflater().inflate(layoutResID,
(ViewGroup) findViewById(R.id.content));
}
}
The base layout is pretty much the same, except everything specific to MainActivity is removed.
<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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<include layout="#layout/toolbar" android:id="#+id/toolbar_layout"/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="304dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:clickable="true"
android:background="#ffffff">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button1"
android:text="Button to Activity1"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
In MainActivity, we no longer need to setup the drawer and toggle.
public class MainActivity extends BaseActivity {
private CollectionPagerAdapter mCollectionPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCollectionPagerAdapter = new CollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
TabLayout tabs = (TabLayout)findViewById(R.id.tabs);
tabs.setupWithViewPager(mViewPager);
}
...
}
And the layout for MainActivity is now basically just the ViewPager and TabLayout.
<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="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/pager">
...
</android.support.v4.view.ViewPager>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/tabs"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/colorPrimaryDark"
app:tabTextColor="#color/tab_text"
app:tabIndicatorColor="#android:color/transparent"
app:tabBackground="#drawable/selected_tab_color"
style="#style/MyCustomTabLayout" />
</LinearLayout>
Then, to accomplish everything in Activity1 that your posted code is doing, all we need is this, since the Toolbar and title TextView are now in BaseActivity.:
public class Activity1 extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classe1);
mTitle.setText("Activity 1");
}
}
And the layout for Activity1 can be pared down significantly:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:overScrollMode="never">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="CLASSE 1"
android:textSize="35sp"
android:gravity="center"/>
</LinearLayout>
</ScrollView>
You call setContentView two times in the Activity1 onCreate method, the first time with R.layout.classe1 and the second time with R.layout.activity_main (when you call the super.onCreate). The last setContentView wins, your problem is here.

Categories

Resources