CollapsingToolbarLayout and toolbar action buttons - java

I would appreciate if someone could give me some pointers to solve my latest issue.
I have an activity with a CollapsingToolbarLayout. In an un-collapsed state Im unable to get the buttons to work. I do not know how to fix this issue. I have searched on stackoverflow before posting this, but I did not find any helpful tips.
Im posting here hoping for an answer
Thanks
This is my code!
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/app_background"
android:fitsSystemWindows="true"
tools:context="com.company.walt.activities.photos.PhotosAAAActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/backdrop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/ip_photo_header"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/love_music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AAAAAA"
android:textColor="#android:color/white"
android:textSize="#dimen/ssi_txt_40sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BBBBBBBB"
android:textColor="#android:color/white"
android:textSize="#dimen/ssi_txt_20sp" />
</LinearLayout>
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_marginTop="#dimen/ssi_24dp"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:tabIndicatorColor="#color/white"
app:tabSelectedTextColor="#color/white"
app:tabTextColor="#color/white" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
PhotosAAAActivity.java
public class PhotosAAAActivity extends AppCompatActivity {
//region WIDGETS
private AppBarLayout bAppBarLayout;
private CollapsingToolbarLayout bCollapsingToolbar;
private Toolbar bToolbar;
private TabLayout mTabLayout;
//endregion
//region VARS
private ViewPager mViewPager;
private PhotosPagerAdapter mPhotosPagerAdapter;
SharedPreferencesManager mSharedPreferences;
//endregion
/* ******************************************************************************************* */
//region THE ONCREATE
#Override
protected void onCreate(Bundle savedInstanceState)
{
//region Load Preferences
mSharedPreferences = new SharedPreferencesManager(this);
//endregion
//region Switching theme style
if (mSharedPreferences.getNightModeState() == true) {
setTheme(R.style.NightTheme);
} else {
setTheme(R.style.LightTheme);
}
//endregion
//region Super onCreate
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
//endregion
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window w = getWindow(); // in Activity's onCreate() for instance
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
//region Calling Methods
setUpCollapsingToolbar();
setUpToolbar();
setViewPager();
//endregion
}
//endregion
private void setUpCollapsingToolbar() {
bCollapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
bCollapsingToolbar.setCollapsedTitleTextColor(getResources().getColor(R.color.white));
bAppBarLayout = (AppBarLayout) findViewById(R.id.appbar);
bAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
bCollapsingToolbar.setTitle("Post photos");
isShow = true;
} else if (isShow) {
bCollapsingToolbar.setTitle("");
isShow = false;
}
}
});
}
/* ******************************************************************************************* */
//region Used to create the toolbar on top
private void setUpToolbar() {
bToolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(bToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
}
//endregion
/* ******************************************************************************************* */
//region Used to create the tab layout
private void setViewPager() {
mViewPager = (ViewPager) findViewById(R.id.pager);
mPhotosPagerAdapter = new PhotosPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mPhotosPagerAdapter);
mTabLayout = (TabLayout) findViewById(R.id.tab);
mTabLayout.setupWithViewPager(mViewPager);
}
//endregion
/* ******************************************************************************************* */
//region MATERIAL DRAWER
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.photo_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case android.R.id.home:
finish();
//Toast.makeText(PhotosAAAActivity.this, "GO BACK", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//endregion
}
UPDATE! - 2018-01-13
I figured out what is cousing the the issue but I still dont know fix this
The problem is that if I remove this code then the tabs won't show up, so it feels as if this ***** with me
The issue
//region Used to create the tab layout
private void setViewPager() {
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
mPhotosPagerAdapter = new PhotosPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mPhotosPagerAdapter);
mTabLayout = (TabLayout) findViewById(R.id.tab);
mTabLayout.setupWithViewPager(mViewPager);
}
//endregion

There are two issues with your code, both related to the buttons you're trying to get to work.
First, with the home button (or the up button you need to activate it with actionBar before handling events with it. Add the following:
getSupportActionBar().setHomeButtonEnabled(true);
inside your setupToolbar method. You can now access the button using the code you've written under the case android.R.id.home:.
The second button has the same issue. You haven't added any logic to handle the button click. Let's say your button on the right has id="#+id/more". Now to define an action for it, you need to put a case with its id inside switch like,
case R.id.more:
//The action needed for the button
break;

try this.
in your activity
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
in your xml
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
//for menu you should give ids to that menu items in your menu file
//R.menu.photo_category and after that if you have 2 menu items
// you have to write listener for every single items for onClick like.
case R.id.item1:
finish();
break;
case R.id.item2:
finish();
break;
}
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();
if (id == android.R.id.home) {
finish();
}
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
Back Button on click listener.

Related

Android NullPointerException Toolbar.setNavigationOnClickListener null object reference

Here is error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.widget.Toolbar.setNavigationOnClickListener(android.view.View$
OnClickListener)' on a null object reference
it happen on
toolBar.setNavigationOnClickListener(new View.OnClickListener()
imageView.setOnClickListener(new View.OnClickListener()
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener()
have the same problem "null object reference".
my team separate file to fragment and all action listener in MainActivity is broke down but we want to separate to fragment like this, but I can't find why separate file to fragment it will null object reference
Here XML fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
xmlns:tools="http://schemas.android.com/tools"
android:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="56dp"
android:background="#color/colorPrimary"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteY="0dp"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<ImageView
android:id="#+id/pamba_icon_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="0dp"
app:layout_constraintLeft_toLeftOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/pambaicon"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
android:layout_marginBottom="0dp"
app:layout_constraintVertical_bias="0.0" />
<ImageView
android:id="#+id/filter_icon_id"
android:clickable="true"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginBottom="8dp"
android:layout_marginRight="48dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
app:layout_constraintRight_toRightOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="#+id/toolbar"
app:srcCompat="#drawable/filter"
app:layout_constraintVertical_bias="0.533" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPaper_id"
android:layout_below="#id/toolbar">
</android.support.v4.view.ViewPager>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottomNavigation_id"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottom_navigation_menu"
app:theme="#style/BottomNavigationTheme"
app:itemBackground="#color/colorGray"/>
</android.support.design.widget.CoordinatorLayout>
</android.support.constraint.ConstraintLayout>
Here activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.constraint.ConstraintLayout
android:id="#+id/contentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
Here MainFragment
import...
public class MainFragment extends Fragment {
public MainFragment() {
super();
}
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
initInstances(rootView);
return rootView;
}
private void initInstances(View rootView) {
// Init 'View' instance(s) with rootView.findViewById here
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
/*
* Save Instance State Here
*/
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save Instance State here
}
/*
* Restore Instance State Here
*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore Instance State here
}
}
}
and MainActivity
import...
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
Toolbar toolBar;
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView imageView;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
setTitle(R.string.title);
drawerLayout = (DrawerLayout) findViewById(R.id.drawe_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
imageView = (ImageView) findViewById(R.id.filter_icon_id);
navigationView.setNavigationItemSelectedListener(this);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolBar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
// set own toolbar
toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
toolBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
drawerLayout.closeDrawer(Gravity.RIGHT);
} else {
drawerLayout.openDrawer(Gravity.RIGHT);
}
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "filter click", Toast.LENGTH_SHORT).show();
}
});
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigation_id);
// select item from bottom navigation
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.firstpage_id:
Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_SHORT).show();
break;
case R.id.offergape_id:
Toast.makeText(getApplicationContext(), "offer", Toast.LENGTH_SHORT).show();
break;
case R.id.needpage_id:
Toast.makeText(getApplicationContext(), "need", Toast.LENGTH_SHORT).show();
break;
case R.id.searchpage_id:
Toast.makeText(getApplicationContext(), "search", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
}
//close drawer when click back
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.END)){
drawerLayout.closeDrawer(GravityCompat.END);
}else {
super.onBackPressed();
}
}
// select item from drawer
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.account_detail_id:
Toast.makeText(getApplicationContext(), "account", Toast.LENGTH_SHORT).show();
break;
case R.id.trip_detail_id:
Toast.makeText(getApplicationContext(), "detail", Toast.LENGTH_SHORT).show();
break;
case R.id.mail_id:
Toast.makeText(getApplicationContext(), "mail", Toast.LENGTH_SHORT).show();
break;
case R.id.logout_id:
Toast.makeText(getApplicationContext(), "logout", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.END);
return true;
}
}
edit add navigation_drawer.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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawe_layout"
android:fitsSystemWindows="true"
tools:openDrawer="end">
<!--set drawer open from right-->
<include layout="#layout/activity_main"/>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/navigation_view"
android:background="#color/colorGray"
android:fitsSystemWindows="true"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/navigation_menu"
app:theme="#style/NavigationDrawerStyle"
android:layout_gravity="end"/>
<!--set drawer open from right-->
</android.support.v4.widget.DrawerLayout>
Your setContentView in onCreate is setting it to R.layout.navigation_drawer. You didn't provide an example of that, but instead provided an example of R.layout.fragment_main. I'm thinking you want that one to be your layout instead. So in onCreate in your activity set your content view to that layout instead:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
... // The rest of your code here
}

Android Toolbar back button not being recognised

I am working on an the settings screens for an android appliation.
The settings screen contains 2 'sub screens' both have a toolbar and a have a back button.
The back button on screen 1 does nothing
The back button on screen 1 works perfectly and returns me to the main settings screen (the 'hard' back button works for both screens)
Screen 1 (Preferences Screen):
Screen 1 xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_preferences"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.clear.pocketcross.Preferences">
<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/colorPrimary"
android:popupTheme="#android:style/ThemeOverlay.Material.Light"
android:theme="#android:style/ThemeOverlay.Material.Dark.ActionBar" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
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">
<Switch
android:id="#+id/counterscroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:defaultValue="true"
android:key="counter_scroll"
android:shadowColor="#color/gradient_mid"
android:shadowDx="5"
android:shadowDy="5"
android:text="#string/scrollCounters"
android:thumb="#drawable/pocketcross_btn_radio_on_holo_light" />
<Switch
android:id="#+id/navswipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:defaultValue="true"
android:key="nav_swipe"
android:shadowColor="#color/gradient_mid"
android:shadowDx="5"
android:shadowDy="5"
android:text="#string/swipeTitle"
android:thumb="#drawable/pocketcross_btn_radio_on_holo_light" />
</LinearLayout>
</RelativeLayout>
Java for Screen 1:
Switch nav;
Switch scroll;
SharedPreferences shared;
public static final String MyPREFERENCES = "PocketCross";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//Toolbar will now take on default Action Bar characteristics
setActionBar(toolbar);
getActionBar().setDisplayHomeAsUpEnabled(true);
this.setTitle("Preferences");
nav = (Switch) findViewById(R.id.navswipe);
scroll = (Switch) findViewById(R.id.counterscroll);
if (shared == null) {
shared = this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}
nav.setChecked(shared.getBoolean("nav_swipe", true));
scroll.setChecked(shared.getBoolean("counter_scroll", true));
nav.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor spEdit = shared.edit();
spEdit.putBoolean("nav_swipe", isChecked);
spEdit.apply();
}
});
scroll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor spEdit = shared.edit();
spEdit.putBoolean("counter_scroll", isChecked);
spEdit.apply();
}
});
}
Screen 2 (Pocket Cross Parameters Screen):
XML for Screen 2:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parametersTable"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*"
android:stretchColumns="*"
android:background="#color/background"
android:clickable="false">
<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/colorPrimary"
android:theme="#android:style/ThemeOverlay.Material.Dark.ActionBar"
android:popupTheme="#android:style/ThemeOverlay.Material.Light" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/parametersList"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginBottom="#dimen/activity_vertical_margin"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
android:layout_below="#+id/toolbar" />
</RelativeLayout>
Java for Screen 2: -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paramaters);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//Toolbar will now take on default Action Bar characteristics
setActionBar(toolbar);
getActionBar().setDisplayHomeAsUpEnabled(true);
this.setTitle(R.string.parametersTitle);
mntFile = MainMenu.mntFile;
fileData = xmlTools.getXmlFile(mntFile);
tags = fileData.xmlTags;
for (int i = 0; i < tags.size(); i++) {
tag = tags.get(i);
if (tag.nodeTag.equalsIgnoreCase("PocketCrossSysParam")) {
nodes = tag.nodeData;
paramSetting = xmlTools.getNodeFromList(nodes, "ParamName");
paramValue = xmlTools.getNodeFromList(nodes, "ParamValue");
parameter = new PocketCrossParameter(paramSetting,paramValue);
parameters.add(parameter);
}
}
loadParams();
}
(loadParams is a function to get the various parameters from an xml file)
I have tried adding the following to my code but still the back button does nothing: -
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
What I am struggling to understand is why the back button on every single screen in my app works perfectly except this one.
I'm guessing it will be something obvious but I have no idea what.
In your manifest.xml add this line, android:parentActivityName=".(Name of the activity you want to return)"
Just like this
<activity
android:name=".(CurrentActivity)"
android:parentActivityName=".(Activity to be returned)"/>
You can check the following
1) Your activity extend AppCompatActivity
2)
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Title");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
3) override the following method
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()== android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
The issue seems to be with your xml file. You have specified your parent layout as clickable false and hence not getting your click calls. Try removing it.

How to add back button arrow functionality in navigation bar

I am beginner programmer and just resent started android developing.
Watched many answers and couldn't find answer witch would fit for me.
I have added back arrow button in my action bar, but couldn't figure out how to add navigation to first loaded screen.
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
TextView text = (TextView) findViewById(R.id.container_text);
Fragment fragment = null;
if (id == R.id.nav_about) {
fragment = DemoFragment.newInstance("about");
text.setText("1");
} else if (id == R.id.nav_settings) {
fragment = DemoFragment.newInstance("nav settings");
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
DemoFragment.java
public class DemoFragment extends Fragment {
public static final String TEXT = "text";
public static DemoFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(TEXT, text);
DemoFragment fragment = new DemoFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_demo, container, false);
String text = getArguments().getString(TEXT);
return view;
}
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
activity_main.xml
<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.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" />
app_bar_main.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="lt.simbal.drawer.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
android:id="#+id/container"
layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
content_main.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="lt.simbal.drawer.MainActivity"
tools:showIn="#layout/app_bar_main">
<TextView
android:id="#+id/container_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MAIN_ACTIVITY" />
fragment_demo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
nav_header_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
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"
android:src="#android:drawable/sym_def_app_icon" />
<TextView
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" />
activity_main_drawer.xml
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_about"
android:icon="#drawable/ic_menu_camera"
android:title="#string/about" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_menu_manage"
android:title="#string/settings" />
</group>
You need to call setHomeAsUpIndicator & setDisplayHomeAsUpEnabled
Set an alternate drawable to display next to the icon/logo/title when
DISPLAY_HOME_AS_UP is enabled. This can be useful if you are using
this mode to display an alternate selection for up navigation, such as
a sliding drawer.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
......
actionBar.setDisplayHomeAsUpEnabled(true); //Set this to true if selecting "home" returns up by a single level in your UI rather than back to the top level or front page.
actionBar.setHomeAsUpIndicator(R.drawable.Your_Icon); // set a custom icon for the default home button
}
Now
For this handling need to override onOptionsItemSelected(MenuItem item) method in your Activity .
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.home:
// Add your LOGIC Here
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
Alright make sure u do declare activity layout as below -
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<!-- The meta-data element is needed for versions lower than 4.1 -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
Now in every activity add below code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
add below code in onCreate
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.back_dark);
}
R.drawable.back_dark is back button image
remove this actionBar.setHomeButtonEnabled(true); from your code
EDITED: found one thing, change below method
#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;
//}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
otherwise your all code is perfect! no need to change naythig
#JonasSeputis: i have use your activity and run in android device its showing toast "Back button clicked" check below code and comment other code for sometime
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
/*DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});*/
}
#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;
}*/
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(), "Back button clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
}
In your
#Override
public boolean onOptionsItemSelected(MenuItem item){
if (id == android.R.id.home){
// add intent to class you wish to navigate
Intent i = new Intent("com.your.package.classname");
startActivity(i);
}
}
just add this line in
onCreate:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Layout displaying ImageView at the bottom of the page

Im using a collapsing toolbar/scrollview in my activity. but my image (.jpg) always displays at the bottom of the page but i want it under the collapsing toolbar.
i have tried the following:
setting the gravity = top, match_parent, fill_parent, android:layout_below, changing the appbarlayout height but none have solved the problem stated.
heres a screenshot:
night_rui.xml
<tools: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="learn.navdrawbase.Rui">
<android.support.design.widget.AppBarLayout
android:id="#+id/MyAp"
android:layout_width="match_parent"
android:layout_height="56dp"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay"
android:layout_below="#+id/dhotelz">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapse_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/evebg">
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/dhotelz"
android:layout_above="#id/MyAp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="top"
android:src="#drawable/dhoteldesc"/>
</RelativeLayout>
</ScrollView>
</tools:android.support.design.widget.CoordinatorLayout>
Rui.java
package learn.navdrawbase;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by User on 2/4/2016.
*/
public class Rui extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.night_rui);
}
}
BaseActivity.java if needed:
public abstract class BaseActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Toolbar mActionBarToolbar;
private DrawerLayout mDrawerLayout;
protected NavigationView mNavigationView;
private ActionBarDrawerToggle mToggle;
/**
* Helper method that can be used by child classes to
* specify that they don't want a {#link Toolbar}
* #return true
*/
protected boolean useToolbar() {
return true;
}
/**
* Helper method to allow child classes to opt-out of having the
* hamburger menu.
* #return
*/
protected boolean useDrawerToggle() {
return true;
}
#Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
getActionBarToolbar();
setupNavDrawer();
}//end setContentView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Global methods as
/*
mImageLoader = new ImageLoader(this);
mHandler = new Handler();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.registerOnSharedPreferenceChangeListener(this);
...
*/
}
protected Toolbar getActionBarToolbar() {
if (mActionBarToolbar == null) {
mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mActionBarToolbar != null) {
// Depending on which version of Android you are on the Toolbar or the ActionBar may be
// active so the a11y description is set here.
mActionBarToolbar.setNavigationContentDescription(getResources()
.getString(R.string.navdrawer_description_a11y));
//setSupportActionBar(mActionBarToolbar);
if (useToolbar()) { setSupportActionBar(mActionBarToolbar);
} else { mActionBarToolbar.setVisibility(View.GONE); }
}
}
return mActionBarToolbar;
}
private void setupNavDrawer() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (mDrawerLayout == null) {
return;
}
// use the hamburger menu
if( useDrawerToggle()) {
mToggle = new ActionBarDrawerToggle(
this, mDrawerLayout, mActionBarToolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
mDrawerLayout.setDrawerListener(mToggle);
mToggle.syncState();
}
else if(useToolbar() && getSupportActionBar() != null) {
// Use home/back button instead
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(ContextCompat
.getDrawable(this, R.drawable.abc_ic_ab_back_mtrl_am_alpha));
}
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mNavigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id) {
case R.id.nav_1:
createBackStack(new Intent(this, MyHome.class));
break;
case R.id.nav_2:
createBackStack(new Intent(this, MyTour.class));
break;
case R.id.nav_3:
createBackStack(new Intent(this, MyTranslator.class));
break;
case R.id.nav_4:
createBackStack(new Intent(this, MySettings.class));
break;
case R.id.nav_5:
createBackStack(new Intent(this, MyAbout.class));
break;
}
closeNavDrawer();
overridePendingTransition(R.anim.enter_from_left, R.anim.exit_out_left);
return true;
}
protected boolean isNavDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
}
protected void closeNavDrawer() {
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
}
/**
* Enables back navigation for activities that are launched from the NavBar. See
* {#code AndroidManifest.xml} to find out the parent activity names for each activity.
* #param intent
*/
private void createBackStack(Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
TaskStackBuilder builder = TaskStackBuilder.create(this);
builder.addNextIntentWithParentStack(intent);
builder.startActivities();
} else {
startActivity(intent);
finish();
}
}
}//end BaseActivity
Try to change your AppBarLayout height.
Add theme in your AppBarLayout.
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="256dp"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
So you need to use theme:
android:theme="#style/AppTheme.AppBarOverlay"
It's the code and works for me :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="eb.collapsetoolbarlayout.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="256dp"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapse_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:fitsSystemWindows="true">
<ImageView
android:id="#+id/bgheader"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
android:background="#drawable/wallpaper2"
app:layout_collapseMode="pin" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="parallax"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>

Cannot customize Navigation Drawer

I need to customize my navigation drawer like following.
Currently I was able to add following part.
No matter how hard I tried to add another text fields, edit texts and images, I couldn't do it.
Here is my sample code.
This is how I added fields in strings.xml
<string-array name="titles">
<item>Hotel</item>
<item>Historical Sites</item>
<item>Shopping</item>
<item>Restaurant</item>
<item>Attractions</item>
<item>wild Life</item>
<item>Tour Service</item>
</string-array>
<array name="icons">
<item>#drawable/ic_hotel</item>
<item>#drawable/ic_historical</item>
<item>#drawable/ic_shopping</item>
<item>#drawable/ic_resturant</item>
<item>#drawable/ic_attraction</item>
<item>#drawable/ic_wildlife</item>
<item>#drawable/ic_tourservices</item>
</array>
Here is my mainactivity.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<!-- Listview to display slider menu -->
<include layout="#layout/drawer_layout" />
Here is my list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:padding="5dp" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:textColor="#ffffff"
android:textSize="20sp" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
</RelativeLayout>
Here is my CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context; List<RowItem> rowItem;
CustomAdapter(Context context, List<RowItem> rowItem) {
this.context = context;
this.rowItem = rowItem;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
RowItem row_pos = rowItem.get(position);
// setting the image resource and title
imgIcon.setImageResource(row_pos.getIcon());
txtTitle.setText(row_pos.getTitle());
return convertView;
}
#Override
public int getCount() {
return rowItem.size();
}
#Override
public Object getItem(int position) {
return rowItem.get(position);
}
#Override
public long getItemId(int position) {
return rowItem.indexOf(getItem(position));
}
}
Here is my mainactivity.java
public class Extract extends ActionBarActivity {
String[] menutitles;
TypedArray menuIcons;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_extract);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId( i, -1));
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.app_name,R.string.app_name)
{
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu(); }
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new MapFragment();
break;
case 1:
fragment = new hotel();
break;
case 2:
fragment = new restaurant();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
// error in creating fragment
Log.e("Extract", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#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_extract, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default :
return super.onOptionsItemSelected(item);
}
}
/*** * Called when invalidateOptionsMenu() is triggered */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState(); }
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
Here is my drawer_layoout.xml
<?xml version="1.0" encoding="utf-8"?>
<DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/slider_list"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#000000"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:layout_weight="1" />
</DrawerLayout>
Please help me to add the image, two text views near image, horizontal line, and the edit text. Thanks in advance
In your MainActivity, add a new field for the LinearLayout, and assign value to it in onCreate()
private LinearLayout mLenear;
mLenear = (LinearLayout)findViewById(R.id.left_drawer);// inside onCreate
Then add following code inside onPrepareOptionsMenu
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mLenear);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
Then change your closeDrawer like this.
mDrawerLayout.closeDrawer(mLenear);
This should resolve your issue. :)
this will be the main layout that you will be using it contain two parts one is the main part which will have the layout of the main screen and the drawer_layout is the layout that has you navigation view layouts
So you will have to create drawer_layout as you want to display and just simply call it here
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/navigationDrawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
// you will have layout that you will use for your main activity or the activity where you are showing your navigation View
</FrameLayout>
// the drawer_layout will define your navigation View
<include layout="#layout/drawer_layout" />
</android.support.v4.widget.DrawerLayout>
In the activity you will get access to your drawer_layout and get access to your views using that object like
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.navigationDrawer);
// Example of getting your view object
ImageView yourImageView = (ImageView) drawerLayout.findViewById(R.id.imageView);
// you can access any your drawerView using that drawerLayout object

Categories

Resources