onOptionsItemSelected not called in fragment with setDisplayHomeAsUpEnabled in AppCompatActivity - android

I searched all day through all similar question and answers, here in stackoverflow, but found no clue why it doesn't work
here some excerpts from my code
Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
setHasOptionsMenu(true);
actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
actionBar.setTitle("Portfolio");
updateGallery();
return rootView;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
public void updateGallery() {
if (activeAlbum>0) {
actionBar.setDisplayHomeAsUpEnabled(true);
} else {
actionBar.setDisplayHomeAsUpEnabled(false);
}
......
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
default:
break;
}
return false;
}
MainActivity:
public class MainActivity extends AppCompatActivity {...}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
....
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
......
}
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);
}
onOptionsItemSelected is fired neither in MainActivity nor in Fragment

Fragments have to declare that they can provide options. Have a look here:
https://developer.android.com/reference/android/app/Fragment.html#setHasOptionsMenu(boolean)
I think you just need to call setHasOptionsMenu(true) in the onCreateView() of your Fragment.

Related

Click on hamburger icon to open/close DrawerLayout [duplicate]

I have this nav drawer which was working perfectly fine.
Refactoring my code I removed all onOptionsItemSelecteds in activities and made all activities inherit from a base activity which extends AppComplatActivity and implements all the necessary methods.
After this clicking on hamburger icon does not work any more even though I have syncstate() and every thing.
Any clues why this is not working?
One of the activities:
public class MainActivity extends BaseActivity implements SearchFilterFragment.OnFragmentInteractionListener {
NavigationView navigationView;
DrawerLayout drawerLayout;
private Tracker mTracker;
#Override
protected void onResume() {
super.onResume();
drawerLayout.openDrawer(GravityCompat.START);
}
#Override
protected void onPostResume() {
super.onPostResume();
mTracker.setScreenName("MainActivity" + "-----");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.openDrawer(GravityCompat.START);
navigationView = (NavigationView) findViewById(R.id.navigation_view_primary);
navigationView.setNavigationItemSelectedListener(new NavigationDrawerListener(this));
setupToolbar();
Haftdong application = (Haftdong) getApplication();
mTracker = application.getDefaultTracker();
}
private void setupToolbar() {
// Show menu icon
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);// will make the icon clickable and add the < at the left of the icon.
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();//for hamburger icon
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
BaseActivity:
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#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_base, 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);
}
}
You're using the four-parameter constructor for ActionBarDrawerToggle, which means you'll have to call the toggle's onOptionsItemSelected() method in MainActivity's onOptionsItemSelected() override in order to open/close the drawer.
For example:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
If you happen to be providing your own Toolbar – e.g., as the support ActionBar (though it's not necessary to set it as such) – then you can instead pass that Toolbar as the third argument in the ActionBarDrawerToggle constructor call. For example:
Toolbar toolbar = findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
The drawer opening/closing will then be handled by ActionBarDrawerToggle internally, and you won't need to call through to the toggle in onOptionsItemSelected().
The setDisplayHomeAsUpEnabled() call is also unnecessary for this setup, which is handy if you don't want to set the Toolbar as the ActionBar.

How to implement setDrawerLockMode or disable navigation drawer

I have a navigation drawer activity with fragments within it by using a fragment container. I have three fragments within it and I need one of it named locate_login to not contain my navigation drawer.
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); //nav drawer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
locate_login fragment = new locate_login();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void onSelectFragment(View v){ //ignore this
Fragment newFragment;
if(v == findViewById(R.id.trigger)){
newFragment = new locate_after();
}
else{
newFragment = new locate_before();
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is my locate_login fragment
public class locate_login extends Fragment{
public locate_login () {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.locate_login, container, false);
// Inflate the layout for this fragment
return rootView;
}
}
I will highly appreciate it if the answer will be detailed since I'm a beginner on Android Studio.
Create a class for some constant parameter. Declare some constant variable like:
Let say StringConstant.java :
public static final int LOCK_DRAWER = 1;
public static final int SHOW_DRAWER = 2;
When navigating from the drawer, use an Intent object as:
If you want to show the drawer, use:
intent.putExtra("SHOW_DRAWER", StringConstant.SHOW_DRAWER);
OR
If you do not want to show the drawer, use:
intent.putExtra("SHOW_DRAWER", StringConstant.LOCK_DRAWER);
Retrieve intent from your fragment class, you say locate_login.
int status = getActivity.getIntent().getIntExtra("SHOW_DRAWER", 0);
Check status:
if (status == String.Constant.LOCK_DRAWER){
lockDrawer();
}
public void lockDrawer() {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
To unlock the drawer:
public void unlockDrawer() {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}

Floating context menu on button click inside Fragment

In my app I have created few buttons in one fragment which will redirect to several activity based on the click. Now if user click button1, they will get a floating context menu conataing the list of the comapny, such as company1, compan2...etc. I have followed this post Opening a floating menu (context menu) in Android? to develop this feature in my app. But the problem is that this code is implemented in Activity, where in my case I want ti implement it in Fragment. I wrote the code but nothig happen with the button click. Now how can I generate this menu on button click
My contextmenu is
<?xml version="1.0" encoding="utf-8"?>
<item android:id="#+id/company_1"
android:title="#string/company_1"></item>
<item android:id="#+id/company_2"
android:title="#string/company_2"></item>
<item android:id="#+id/company_3"
android:title="#string/company_3"></item>
<item android:id="#+id/company_4"
android:title="#string/company_4">
</item>
<item android:id="#+id/company_5"
android:title="#string/company_5"></item>
<item android:id="#+id/company_6"
android:title="#string/company_6">
</item>
My Fragment Class is
public class MainFragment extends Fragment implements View.OnClickListener{
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button button1=(Button) view.findViewById(R.id.button1);
button1.setOnClickListener(this);
registerForContextMenu(button);
Button button2=(Button) view.findViewById(R.id.button2);
button2.setOnClickListener(this);
Button button3=(Button) view.findViewById(R.id.button3);
button3.setOnClickListener(this);
// Inflate the layout for this fragment
return view;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if(v.getId()==R.id.button1){
this.getActivity().getMenuInflater().inflate(R.menu.contextmenu_company,menu);
}
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
setHasOptionsMenu(true);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.company_1:
Toast.makeText(getActivity().getApplicationContext(),"caompany1code",Toast.LENGTH_LONG).show();
return true;
case R.id.company_2:
......
case R.id.company_3:
.....
case R.id.company_4:
....
return true;
case R.id.company_5:
.....
return true;
case R.id.company_6:
.....
return true;
}
return super.onContextItemSelected(item);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
Toast.makeText(getActivity(),"My colleagues clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Toast.makeText(getActivity(), "News clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.button3:
Toast.makeText(getActivity(), "Navigator clicked", Toast.LENGTH_SHORT).show();
break;
}
}
In MainActivity Class
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
.....
}
Well i found something here :
Try this in your fragment :
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
if(v.getId()==R.id.button1{getActivity().getMenuInflater().inflate(R.menu.contextmenu_company,menu);
}
}
You are also calling this wrong:
//Instead of button use button1.
registerForContextMenu(button1);
Maybe this will help.
You did use
onCreateOptionsMenu(Menu menu)
in your Activity but you are trying to use
onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo)
in your fragment.
Use onCreateOptionsMenu(Menu menu) in your fragment as well and set setHasOptionsMenu(true) in your onCreateView method.

Clicking hamburger icon on Toolbar does not open Navigation Drawer

I have this nav drawer which was working perfectly fine.
Refactoring my code I removed all onOptionsItemSelecteds in activities and made all activities inherit from a base activity which extends AppComplatActivity and implements all the necessary methods.
After this clicking on hamburger icon does not work any more even though I have syncstate() and every thing.
Any clues why this is not working?
One of the activities:
public class MainActivity extends BaseActivity implements SearchFilterFragment.OnFragmentInteractionListener {
NavigationView navigationView;
DrawerLayout drawerLayout;
private Tracker mTracker;
#Override
protected void onResume() {
super.onResume();
drawerLayout.openDrawer(GravityCompat.START);
}
#Override
protected void onPostResume() {
super.onPostResume();
mTracker.setScreenName("MainActivity" + "-----");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.openDrawer(GravityCompat.START);
navigationView = (NavigationView) findViewById(R.id.navigation_view_primary);
navigationView.setNavigationItemSelectedListener(new NavigationDrawerListener(this));
setupToolbar();
Haftdong application = (Haftdong) getApplication();
mTracker = application.getDefaultTracker();
}
private void setupToolbar() {
// Show menu icon
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);// will make the icon clickable and add the < at the left of the icon.
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();//for hamburger icon
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
BaseActivity:
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#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_base, 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);
}
}
You're using the four-parameter constructor for ActionBarDrawerToggle, which means you'll have to call the toggle's onOptionsItemSelected() method in MainActivity's onOptionsItemSelected() override in order to open/close the drawer.
For example:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
If you happen to be providing your own Toolbar – e.g., as the support ActionBar (though it's not necessary to set it as such) – then you can instead pass that Toolbar as the third argument in the ActionBarDrawerToggle constructor call. For example:
Toolbar toolbar = findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
The drawer opening/closing will then be handled by ActionBarDrawerToggle internally, and you won't need to call through to the toggle in onOptionsItemSelected().
The setDisplayHomeAsUpEnabled() call is also unnecessary for this setup, which is handy if you don't want to set the Toolbar as the ActionBar.

toolbar and navigation on it

The project has the activity of the toolbar. Activity in dynamically changing fragments. Depending on the fragment ought to change content toolbar.
Turning to the second fragment ought to appear in the toolbar nazat arrow which returns to the previous fragment.
public class StartPageActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private Toolbar mToolbar;
private NavigationView mNavigationView;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_page_activity);
setTitle("ForgetFul");
getFragment(new MainFragment());
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mNavigationView = (NavigationView) findViewById(R.id.main_drawer);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_widget);
drawerToggle
= new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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) {
Log.i("Activity", "Setting");
return true;
}
if (android.R.id.home == id) {
Log.i("One", "Dude");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}...
In the active from the start displayed MainFragment.
In the second activity, I use the following code:
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
"Up" Arrow appeared, but when I click on arrow, all time open the NavigationView.
how to fix it?
P.S. Sorry for English :(
Try this.
First, remove implements NavigationView.OnNavigationItemSelectedListener , and also comment out the overidden methods and variables.
Then overide the Activity's onBackPressed() method like this:
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getFragmentManager();
if (fragmentManager.getBackStackEntryCount() != 0) {
fragmentManager.popBackStack();
} else {
super.onBackPressed();
}
}
This will make sure that the previous fragments are getting displayed on pressing the Back key.
Then, simply call it in onOptionsItemSelected() method:
if (id == android.R.id.home) {
onBackPressed();
return true;
}

Categories

Resources