Reputation: 165
I've a drawer layout in my main activity. On selecting one of its menu item i.e Social (in my case), it jumps to another activity containing fragments tab layout. The toolbar in my Social activity has a back button <- like this. I want this to work and return to main content activity but i don't know :
where should i do this? Here is the code of Social.Java , where i think needs some change for back button appearing automatically on toolbar but not working.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_social);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
Upvotes: 1
Views: 89
Reputation: 3561
First step:Add this code in onCreat
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Step:2 override onOptionItemSelected
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Upvotes: 2
Reputation: 5534
Try this way
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
....
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// do your work
}
return super.onOptionsItemSelected(item);
}
Upvotes: 0