How to change Android toolbar view? - android

I'm working with the new android toolbar.
/* Jump into, after the user clicks on a listview item */
private void toogleToolbar() {
if (isStandardToolbar)
customToolbar();
else
originalToolbar();
isStandardToolbar = !isStandardToolbar;
}
/* Called inside onCreate and if nothing was clicked */
private void originalToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
/* Called after an click event */
private void customToolbar() {
LayoutInflater inflater = this.getLayoutInflater();
Toolbar toolbar = (ToolBar) inflater.inflate(R.layout.newtoolbar, null);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
It works so far, but now I want to change the toolbar view, after clicking on a list element.
That's my problem, because the last code snippet doesn't produce an exception or other issues, so it should be all ok. But I see only the "old" toolbar. I tried to set visibility to GONE or INVISIBLE to the old one, but it doesn't have any effect.
In my activity_main.xml, I include R.id.toolbar, but I think, the second code must overwrite the old one!?
EDIT:
AFAIK, the new toolbar should replace the old actionBar. Toolbar is used to place navigation or other, specific content. I my case, I want to create a small action menu, where the user can edit or delete a list item.

I found the solution to your question (maybe its too late...) but below is the code I used to make it :
MainActivity.java :
package fr.zwedge.sot;
import android.app.*;
import android.os.*;
import android.support.v7.app.*;
import android.support.v7.widget.*;
import android.view.*;
import android.widget.*;
import android.view.View.*;
public class MainActivity extends AppCompatActivity {
boolean isStandardToolbar = true;
android.support.v7.widget.Toolbar toolbar = null, newToolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initToolbars();
((Button)toolbar.findViewById(R.id.tbt)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
toogleToolbar();
}
});
((Button)newToolbar.findViewById(R.id.tbt2)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
toogleToolbar();
}
});
}
/* Jump into, after the user clicks on a listview item */
private void toogleToolbar() {
if (isStandardToolbar)
customToolbar();
else
originalToolbar();
isStandardToolbar = !isStandardToolbar;
}
private void initToolbars() {
if (toolbar == null)
toolbar = (android.support.v7.widget.Toolbar)findViewById(R.id.toolbar);
if (newToolbar == null)
newToolbar = (android.support.v7.widget.Toolbar)findViewById(R.id.newtoolbar);
}
/* Called inside onCreate and if nothing was clicked */
private void originalToolbar() {
toolbar.setVisibility(View.VISIBLE);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
/* Called after an click event */
private void customToolbar() {
toolbar.setVisibility(View.GONE);
setSupportActionBar(newToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(true);
}
}
And here are the two toolbars in main.xml :
<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.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/holo_green_dark"
android:background="#FF008F12">
<Button
android:text="Bla bla bla"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbt" />
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.Toolbar
android:id="#+id/newtoolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:titleTextColor="#android:color/holo_green_dark"
android:background="#FF8F0800">
<Button
android:text="Change once again"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tbt2" />
</android.support.v7.widget.Toolbar>
<TextView
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_view" />
Hope it helps you, Darkball60

Related

Android Navigation Drawer with multiple Activity

I am trying to create a BaseActivity with navigation drawer and extend it in other activities so that I can reuse the the navigation drawer code.
What I have figured out so far:
I can use fragments to do this (which I can do).
I can use a BaseActivity and inflate the content area (Frame layout with id as “main_container” in my case) to show other activities. In this case I have figured out how to click on navigation drawer items to change activity.
However, when I have a button inside one of my activity (example activityA) and I want to load another activity (activityB), show a toast, etc. by clicking that button, the click listener does not work unless I write the code for the listener inside the onCreate method of the BaseActivity.
To me this does not make sense because it forces me to write all the codes inside the BaseActivity which is not the most efficient way of writing code (the activities acts like fragments so I can just use fragments instead).
What I want to know is, how to load the navigation drawer on all activities extending the BaseActivity, and still allow the activities to retain their behaviours.
Code samples
My activity_home.xml (BaseActivity)
<?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"
android:id="#+id/drawer_layout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeActivity"
tools:openDrawer="start"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/custom_tool"
layout="#layout/custom_bar"/>
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/nav_display"
app:menu="#menu/nav_drawer_menu"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"/>
</android.support.v4.widget.DrawerLayout>
activity_main.xml (activityA)
<?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=".MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="0dp"
android:layout_height="147dp"
android:layout_marginStart="105dp"
android:layout_marginLeft="105dp"
android:layout_marginTop="150dp"
android:layout_marginEnd="105dp"
android:layout_marginRight="105dp"
android:layout_marginBottom="48dp"
android:contentDescription="#string/app_logo"
app:layout_constraintBottom_toTopOf="#+id/search_bar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:srcCompat="#mipmap/ic_launcher" />
<SearchView
android:id="#+id/search_bar"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginStart="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="48dp"
android:layout_marginEnd="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="50dp"
android:background="#drawable/input_default"
android:gravity="center"
app:layout_constraintBottom_toTopOf="#+id/search_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView" />
<Button
android:id="#+id/search_button"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginStart="150dp"
android:layout_marginLeft="150dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="150dp"
android:layout_marginRight="150dp"
android:layout_marginBottom="228dp"
android:background="#drawable/button_default"
android:text="#string/search"
android:textColor="#color/colorAccent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/search_bar" />
</android.support.constraint.ConstraintLayout>
When the app is initially loading the “main_content” of the BaseActivity is inflated with the activity_main layout.
When I clicked the search_button inside the activity_main.xml, I want to load another activity which is only happening when I am writing the code inside the base activity.
HomeActivity
package com.example.naisse;
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.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;
public class HomeActivity extends AppCompatActivity {
protected static int position;
private DrawerLayout drawer;
protected FrameLayout frames;
Button searchButton;
/**
* This flag is used just to check that launcher activity is called first time
* so that we can open appropriate Activity on launch and make list item position selected accordingly.
* */
private static boolean isLaunch = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.custom_tool);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
frames = findViewById(R.id.main_container);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
/*inflating the layout with activity_main*/
getLayoutInflater().inflate(R.layout.activity_main, frames);
searchButton = findViewById(R.id.search_button);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*removing the activity_main and inflating they layout with activity_result*/
frames.removeAllViews();
getLayoutInflater().inflate(R.layout.activity_result, frames);
}
});
}
#Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
}
Extending MainActivity with HomeActivity
MainActivity
package com.example.naisse;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends HomeActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
How to solve this issue?
I am surprised so few are interested in doing this in all these years. Maintaining the duplicated code of the DrawerLayout stuff in xml files of all activities is pretty silly.
I tried the self-answer from #Mill3r, unfortunately overriding setContentView conflicts with databinding and causes crash.
Instead of setContentView I create a method in the base activity like:
public void setContent(View contentView) {
// Find the content container
frames = findViewById(R.id.main_container);
frames.removeAllViews();
frames.addView(contentView);
// The rest of the base setup
Toolbar toolbar = findViewById(R.id.custom_tool);
setSupportActionBar(toolbar);
drawer = 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();
}
Then in all activities derided from the base, call this function after setting databinding, like:
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
setContent(binding.getRoot());
For answer and understanding, please read the discussion between me and Mike M.
What I was initially doing was inflating the "main_container" with layout and therefore the Activity class was not getting triggered. To do that, I had to override setContentView() method inside the BaseActivity (HomeActivity in my case) and put every sharable code such as toolbar and navigation drawer inside that.
My new HomeActivity.class
public class HomeActivity extends AppCompatActivity {
private DrawerLayout drawer;
protected FrameLayout frames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
#Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
#Override
public void setContentView(int layoutResID) {
// Set the base layout
super.setContentView(R.layout.activity_home);
// Find the content container
frames = findViewById(R.id.main_container);
// Inflate the extending Activity's layout into it
getLayoutInflater().inflate(layoutResID, frames);
// The rest of the base setup
Toolbar toolbar = findViewById(R.id.custom_tool);
setSupportActionBar(toolbar);
drawer = 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();
}
}
And now the toolbar and navigation drawer is shared across all activities.

Title not showing in Toolbar when part of DrawerLayout

I'm new to Android programming.
I'm trying to replicate an IOS app of mine while learning the ropes.
I'm not using Android Studio wizards to create any activities - doing everything manually so that I may understand what goes on.
I've setup an AppCompat activity using a DrawerLayout and a toolbar.
Initially, before I noticed the existence of DrawerLayout I had setup the same overall design using a RelativeLayout.
While my Toolbar was inside the Relative Layout, I could set its title without a problem.
When I replaced RelativeLayout and put the Toolbar inside the DrawerLayout the title stopped displaying.
I can see in the debugger that the title is getting set correctly, it just does not show up.
I have currently tied up an ActionBarDrawerToggle with DrawerLayout.
Previously, I was not using an ActionBarDrawerToggle.
In both cases, Toolbar title is not displaying.
If I restore RelativeLayout, the title is showing up again.
I have searched everywhere in SO but can't find a solution.
Layout for the activity is this:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/app_drawer">
<include layout="#layout/toolbar"/>
<FrameLayout
android:id="#+id/fragment_items_list_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:layout_marginTop="52dp"
/>
<LinearLayout
android:orientation="vertical"
android:layout_width="256dp"
android:layout_height="match_parent"
android:background="#color/lightGray"
android:id="#+id/fragment_nav_list_container"
android:layout_gravity="start"
/>
Layout for the toolbar is this:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_height="52dp"
android:layout_width="match_parent"
android:minHeight="52dp"
android:background="?attr/colorPrimary">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="App Title"
android:gravity="center"
android:textColor="#ffffff"
android:textSize="20dp"
android:textStyle="bold"
android:background="#color/red"
/>
Code for the activity is this:
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
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.util.Log;
import android.view.View;
import android.widget.TextView;
import DatabaseMaster;
public class MainWrapperActivity extends AppCompatActivity {
class MainWrapperDrawerToggle extends ActionBarDrawerToggle {
public MainWrapperDrawerToggle(Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
super(activity, drawerLayout, openDrawerContentDescRes, closeDrawerContentDescRes);
}
public MainWrapperDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);
}
// Drawer Listener
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView,slideOffset);
Log.d("debug","Main App Drawer: SLIDE");
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Log.d("debug","Main App Drawer: OPENED");
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.d("debug","Main App Drawer: CLOSED");
}
#Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
Log.d("debug", "Main App Drawer: STATE CHANGED: " + newState);
}
}
private MainWrapperDrawerToggle mActionBarDrawerToggle;
private DrawerLayout mDrawerLayout;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wrapper);
// Add / Configure Toolbar
mToolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
// Setup App Drawer
mDrawerLayout=(DrawerLayout)findViewById(R.id.app_drawer);
mActionBarDrawerToggle=new MainWrapperDrawerToggle(this,mDrawerLayout,mToolbar,R.string.app_name,R.string.app_name);
mDrawerLayout.addDrawerListener(mActionBarDrawerToggle);
//getSupportActionBar().setHomeButtonEnabled(true);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
//mActionBarDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_nav_menu);
// Add Fragment(s)
FragmentManager fm=getSupportFragmentManager();
// Check for existing fragment by the ID of its Container
Fragment fragment=fm.findFragmentById(R.id.fragment_items_list_container);
if (fragment == null) {
fragment=new SectionsListFragment();
// Add fragment to it's Container
fm.beginTransaction().add(R.id.fragment_items_list_container,fragment).commit();
}
}
#Override
protected void onPostCreate (Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mActionBarDrawerToggle.syncState();
mToolbar.setNavigationIcon(R.drawable.ic_nav_menu);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onStart () {
super.onStart();
}
#Override
protected void onResume () {
super.onResume();
TextView toolbarTitleView=(TextView)mToolbar.findViewById(R.id.toolbar_title);
toolbarTitleView.setText(R.string.app_name);
}
#Override
protected void onDestroy () {
DatabaseMaster.getInstance().getRealm().close();
DatabaseMaster.getInstance().setRealm(null);
super.onDestroy();
}
#Override
public boolean onSupportNavigateUp () {
Log.i("debug", "Toggling hamburger menu");
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
mDrawerLayout.openDrawer(GravityCompat.START);
}
return false;
}
}
DrawerLayout only contains two childs i.e. only two layouts. You can replace your FrameLayout with another RelativeLayout and place your FrameLayout and include tag in that new RelativeLayout.
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/app_drawer">
<include layout="#layout/new_container"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="256dp"
android:layout_height="match_parent"
android:background="#color/lightGray"
android:id="#+id/fragment_nav_list_container"
android:layout_gravity="start"/>
</android.support.v4.widget.DrawerLayout>
And in Relative Layout Use this
<RelativeLayout
android:id="#+id/new_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/toolbar"/>
<FrameLayout
android:id="#+id/fragment_items_list_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"/>
</RelativeLayout>
Rest is fine.Hope This Help.

Two toolbars are visible in my fragment

I have been working on a navigation drawer using toolbar and while clicking on the drawer items , respective fragments will be displayed,but here is the problem,when ever I am clicking the drawer items ,fragments with two toolbars are displayed.please help.
fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="archerpenny.impdrawerfragment.BlankFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<!-- TODO: Update blank fragment layout -->
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</LinearLayout>
</FrameLayout>
My Activity_main.xml..
`<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/Container"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hi"/>
</FrameLayout>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/DrawerList"
android:layout_marginTop="?android:attr/actionBarSize"
android:background="#mipmap/menu_bg"
android:layout_gravity="left"/>
</android.support.v4.widget.DrawerLayout>
MainActivity.java....
`
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle mDrawerToggle;
RecyclerView.Adapter mAdapter;
RecyclerView recyclerView;
DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new NavigationDrawerAdapter(this);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationDrawerAdapter adapter;
recyclerView = (RecyclerView)findViewById(R.id.DrawerList);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(mAdapter);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,toolbar,R.string.open,R.string.close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(MainActivity.this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// do whatever
if(position==0)
{
BlankFragment blankFragment=new BlankFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.Container, blankFragment)
.commit();
}
mDrawerLayout.closeDrawers();
}
})
);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
BlankFragment.java
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BlankFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
return fragment;
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
AppCompatActivity activity = (AppCompatActivity) getActivity();
View view=inflater.inflate(R.layout.fragment_blank, container, false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Inflate the layout for this fragment
return view;
}
}
Remove the include statement in your fragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="archerpenny.impdrawerfragment.BlankFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- TODO: Update blank fragment layout -->
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</LinearLayout>
For those who came here from search for two Toolbars in a fragment.
There is a similar topic: Double Toolbar Is Showing on Fragment.
In AndroidManifest set a theme:
<activity
android:name=".YourActivity"
android:label="#string/title"
android:theme="#style/AppTheme.NoActionBar" />
The theme is:
<style name="AppTheme.NoActionBar" parent="AppTheme">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>
In YourActivity extend it from AppCompatActivity and add ActionBar, so write:
class YourActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fragment)
setToolbar(toolbar)
showFragment()
// Handle onResume() in fragments, if needed.
supportFragmentManager.addOnBackStackChangedListener {
supportFragmentManager.fragments.lastOrNull()?.onResume()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// 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.
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
fun setToolbar(toolbar: Toolbar) {
setSupportActionBar(toolbar)
// Show back arrow.
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
// Additional settings, if needed.
toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.white))
val toolbarTextColor = ContextCompat.getColor(this, R.color.blue)
toolbar.setTitleTextColor(toolbarTextColor)
toolbar.navigationIcon?.setColorFilter(toolbarTextColor, PorterDuff.Mode.SRC_ATOP)
toolbar.overflowIcon?.setColorFilter(toolbarTextColor, PorterDuff.Mode.SRC_ATOP)
}
private fun showFragment() {
if (supportFragmentManager.findFragmentByTag(YourFragment.TAG) == null) {
val fragment = YourFragment.newInstance()
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment, YourFragment.TAG)
.commit()
}
}
}
This is a layout for YourActivity:
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<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="?android:attr/actionBarSize"
app:popupTheme="#style/AppTheme.PopupOverlay"
/>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</android.support.design.widget.CoordinatorLayout>
Previous attempts (do not repeat).
I made many experiments. Created a new project. Copied all suspecting activities and fragments, styles, colors, strings, dimens, changed AndroidManifest. Set a theme of the activity not from ...NoActionBar style. Removed Toolbar with surrounding <android.support.design.widget.AppBarLayout> tag in activity layout. In onCreate() wrote:
// setSupportActionBar(toolbar) // Crashing string.
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
Then I copied the project to another folder and after compilation it showed one Toolbar. Even if in the source folder I launched File > Invalidate caches and Restart, nothing happened. So, after invalidating caches, Build > Rebuild Project (probably Build > Clean Project) it showed one Toolbar. I even returned back AppBarLayout. I blamed Android Studio.
But on the next day this magic stopped to execute. I compiled the same project and again got two Toolbars. And copying folders, invalidating, deleting /build folders didn't help. So I began to research repository commits in order to catch a solution. It is written in the beginning of the answer.

Hide support ActionBar while scrolling

I have an activity that has a support action bar, below that a sliding tab layout, below that a listview of images for the corresponding tab. I just want to hide the support action bar not the sliding tab strip and I am not able to hide it.
Here is my activity:
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
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.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
public class NewGalleriActivity extends AppCompatActivity implements ViewTreeObserver.OnScrollChangedListener {
Toolbar toolbar;
ViewPager viewPager;
NewGalleriPagerAdapter viewPagerAdapter;
SlidingTabLayout slidingTabLayout;
CharSequence Titles[] = {"Wildlife", "Architecture", "Black & White", "Close Up", "Night"};
int numOfTabs = 5;
private float mActionBarHeight;
private ActionBar mActionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_galleri);
final TypedArray styledAttributes = getTheme().obtainStyledAttributes(
new int[]{android.R.attr.actionBarSize});
mActionBarHeight = styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
//Initialise views
viewPager = (ViewPager) findViewById(R.id.pager);
slidingTabLayout = (SlidingTabLayout) findViewById(R.id.tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
mActionBar = getSupportActionBar();
int defaultValue = 0;
int page = getIntent().getIntExtra("ARG_PAGE", defaultValue);
viewPagerAdapter = new NewGalleriPagerAdapter(getSupportFragmentManager(), Titles, numOfTabs);
viewPager.setAdapter(viewPagerAdapter);
viewPager.setCurrentItem(page);
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return Color.parseColor("#FAC80A");
}
});
slidingTabLayout.setViewPager(viewPager);
if (android.os.Build.VERSION.SDK_INT >= 21)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(Color.parseColor("#263238"));
}
FloatingActionButton button = (FloatingActionButton) findViewById(R.id.ddd);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(NewGalleriActivity.this, ImageGridActivity.class);
startActivity(intent);
}
});
findViewById(R.id.parent).getViewTreeObserver().addOnScrollChangedListener(this);
}
#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_home, 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);
}
#Override
public void onScrollChanged() {
float y = findViewById(R.id.parent).getScrollY();
if(y >= mActionBarHeight && mActionBar.isShowing()) {
mActionBar.hide();
} else if(y==0 && !mActionBar.isShowing()) {
mActionBar.show();
}
}
}
Here is my layout for the activity:
<?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:background="#drawable/black"
android:orientation="vertical">
<include layout="#layout/toolbar2" />
<com.pipipzz.simpleapp.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#231F20" />
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#drawable/drop_shadows" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/ddd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="24dp"
android:layout_marginBottom="10dp"
android:src="#drawable/fab_icons"
app:borderWidth="#null"
app:elevation="4dp"
app:fabSize="normal" />
</FrameLayout>
</ScrollView>
</LinearLayout>
Here is my layout for the toolbar:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFC80A"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<ImageView
android:id="#+id/tool_logo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="#string/tool_logo"
android:gravity="center_horizontal"
android:src="#drawable/logo_tool" />
</RelativeLayout>
<ImageView
android:id="#+id/tool_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="8dp"
android:contentDescription="#string/tool_search"
android:src="#drawable/search" />
</android.support.v7.widget.Toolbar>
Edit: Here is my layout for fragment that is shown in the tabs.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#231F20"
tools:context="com.pipipzz.simpleapp.ArchitectureFragment">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#null"
android:dividerHeight="0dp"
android:scrollingCache="true"
android:smoothScrollbar="true" />
</FrameLayout>
Any help would be highly appreciated.
Please have a look at this library Android-ObservableScrollView
It has a lot of examples and it will be much easier to use it in your case.
There are several examples of using it with Toolbar, that you are currently using in your code.
It would be better if you prodived all source code to run it, maybe you have issue somewhere else.
First about your code. Don't use findViewById whenever you want, it is really heavy method. So when you are doing this each time onScrollViewChanged it makes your app laggy.
Find your scroll view only once in onCreate method
mMainScrollView = findViewById(R.id.parent);
mMainScrollView.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {#Override
public void onScrollChanged() {
int scrollY = rootScrollView.getScrollY(); //for verticalScrollView
// Hide or show toolbar here
}
});
Why not directly to call hide on toolbar without getting support
action bar ? Try do to it directly on toolbar.
If you call hide
method directly on ActionBar/Toolbar does it work ?
Try to do something like this
To hide toolbar
toolbar.animate().translationY(-toolbar.getBottom()).setInterpolator(new AccelerateInterpolator()).start();
And show it again
toolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).start();

Toolbar using drawable at background doesn't display home button within Motorola device

When i use a drawable at toolbar background, the home button isn't displayed. Curiously, i just notice that in Motorola device's.
here's the xml layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#drawable/topo"
android:elevation="4dp"
android:minHeight="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<FrameLayout
android:layout_below="#id/toolbar"
android:id="#+id/drawer_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- the layout which will be the content of the activity (which will be hosted inside the drawer (NOT the list of the drawer)) -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtLabel"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:textSize="16sp" />
</FrameLayout>
</FrameLayout>
</RelativeLayout>
here's then activity:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.mikepenz.iconics.typeface.FontAwesome;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.SectionDrawerItem;
public class CustomContainerActivity extends AppCompatActivity {
//save our header or result
private Drawer result = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_custom_container_dark_toolbar);
// Handle Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//Create the drawer
result = new DrawerBuilder(this)
//this layout have to contain child layouts
.withRootView(R.id.drawer_container)
.withToolbar(toolbar)
.withActionBarDrawerToggleAnimated(true)
.addDrawerItems(
new PrimaryDrawerItem().withName("teste 1").withIcon(FontAwesome.Icon.faw_home),
new PrimaryDrawerItem().withName("teste 1").withIcon(FontAwesome.Icon.faw_gamepad),
new PrimaryDrawerItem().withName("teste 1").withIcon(FontAwesome.Icon.faw_eye),
new SectionDrawerItem().withName("teste 1"),
new SecondaryDrawerItem().withName("teste 1").withIcon(FontAwesome.Icon.faw_cog),
new SecondaryDrawerItem().withName("teste 1").withIcon(FontAwesome.Icon.faw_question).setEnabled(false),
new SecondaryDrawerItem().withName("teste 1").withIcon(FontAwesome.Icon.faw_github),
new SecondaryDrawerItem().withName("teste 1").withIcon(FontAwesome.Icon.faw_bullhorn)
)
.withSavedInstance(savedInstanceState)
.build();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the drawer to the bundle
outState = result.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
//handle the back press :D close the drawer first and if the drawer is closed close the activity
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
} else {
super.onBackPressed();
}
}
}
http://i.stack.imgur.com/eiDbK.png
Screen at GenyMotion emulator: Motorola Moto X at left, Samsung S5 at right
The problem occurs in real devices too.
Previewsly, thanks for any help

Categories

Resources