I'm trying to start up a preference fragment from a MenuItem and I'm having some trouble. I followed a tutorial on how to make a listPreference and then adapted it to my project, but it crashes the app.
This is the item in which is the launch point for the intenet to the prefFrag:
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/settings"
android:onClick="prefStartup"/>
Here is the code that launches the intent in the main activity:
public void prefStartup(MenuItem item){
Intent intentSetPref = new Intent(getApplicationContext(), PrefActivity.class);
startActivityForResult(intentSetPref, 0);
}
Here are the two classes that help display the fragment (straight from the tutorial):
public class PrefActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PrefFragment prefFragment = new PrefFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, prefFragment);
fragmentTransaction.commit();
}
}
public class PrefFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
}
I'm not really sure why it would be breaking if the stuff is straight from the tutorial. In the tutorial though they just launch it from a regular button rather than a MenuItem.
I followed the same tutorial as you not long ago and managed to stumble my way through the same problem.
Instead of using your prefStartup() try the following in your main activity.
//Method for creating options menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//Method for handling options menu selection
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_settings was selected
case R.id.action_settings:
Intent intentSetPref = new Intent(getApplicationContext(), PrefActivity.class);
startActivityForResult(intentSetPref, 0);
break;
default:
break;
}
return true;
}
You can remove the android:onClick="prefStartup" from your menu xml as well.
Related
I have an android Activity with a bottom menu navigation bar, That navigates between three fragments and a single top menu item that should open a new activity, But the top menu ActionBar item is not responding to click events. Maybe there is something am missing? Or should I be handling the menu from within my fragments?
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Set Network Connection Listener
setConnectionListener(this);
//check the network connectivity when activity is created
checkConnection();
BottomNavigationView bottomNavigation = (BottomNavigationView) findViewById(R.id.bottom_navigation);
bottomNavigation.setOnNavigationItemSelectedListener(this);
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, HomeFragment.newInstance());
transaction.commit();
// Used to select item programmatically
// bottomNavigation.getMenu().getItem(0).setChecked(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.top, menu);
// return super.onCreateOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(TAG, "Menu Clicked " + item.getItemId());
switch (item.getItemId()){
case R.id.tab_cart:
Intent intent = new Intent(this, CartActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
My Menu top.xml res menu file
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.shopcentra.activities.MainActivity">
<item
android:id="#+id/tab_cart"
android:icon="#mipmap/cart"
android:title="#string/cart"
app:actionLayout="#layout/notification_layout"
app:showAsAction="always">
</item>
</menu>
I can't see where you've added a View.OnClickListener on the "tab_cart". If you have set one, please share that code as well otherwise, add an OnCLickListener on that view and see if the problem persists then as well.
EDIT: code to add OnClickListener on menu item:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem tabCartMenuItem = menu.findItem(R.id.tab_cart);
View notificationActionView = menuItem.getActionView();
notificationActionView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(tabCartMenuItem));
}
});
}
Try adding this code to your onCreateOptionsMenu() method.
I am building a calculator app using fragment and I want the calculator fragment to show back when the back button is pressed on the menu item fragment. I have been using the addToBackStac(null) but it is not working for me.
Here is my code below
public class MainActivity extends ActionBarActivity {
FragmentManager fragmentManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null){
fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().addToBackStack(null);
CalculatorFragment calc = new CalculatorFragment();
fragmentTransaction.add(R.id.relLejaut, calc);
fragmentTransaction.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#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 == R.id.item) {
About about= new About();
// Insert the fragment by replacing any existing fragment
fragmentManager.beginTransaction().addToBackStack(null).replace(R.id.relLejaut, about).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
}
You need to first add() or replace() a fragment in FragmentTransaction and then call addToBackStack() for it to work.
Call it this way:
fragmentManager.beginTransaction().replace(R.id.relLejaut,about).addToBackStack(null).commit();
I have an ActionBar activity with a FrameLayout and a menu. when the user clicks the menu item I replace the fragment with the relevant new fragment. However, I cannot see an obvious way to remove the menu item for the selected fragment.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
StudyFragment startFragment = new StudyFragment();
startFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add
(R.id.container, startFragment).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_study:
replaceFragment((Fragment)new StudyFragment());
break;
case R.id.action_list:
replaceFragment((Fragment)new ListFragment());
break;
// etc
}
return super.onOptionsItemSelected(item);
}
private void replaceFragment(Fragment f) {
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, f);
transaction.addToBackStack(null);
transaction.commit();
}
The Google documentation on changing menus says to disable the menu in onPrepareOptionsMenu - but how will I know which item has been selected?
--Solution Implemented--
Using Muhammed Refaat's solution below I added two new members to the class:
private Menu activityMenu;
private MenuItem curMenuItem;
Set them in onCreateOptionsMenu
activityMenu = menu;
curMenuItem = activityMenu.findItem(R.id.action_study);
curMenuItem.setVisible(false);
And changed them on onOptionsItemSelected
curMenuItem.setVisible(true);
curMenuItem = activityMenu.findItem(id);
curMenuItem.setVisible(false);
First get the item you want to remove :
MenuItem item = menu.findItem(R.id.your_action);
then set it's Visibility false :
item.setVisible(false);
and if the problem is in getting the menu (as it's not in the fragment), you can easily get a context from the activity that contains the menu and get the menu by it.
Inside your fragment you will have to use setHasOptionsMenu(true); in order to access options menu from within your fragment.
Code (inside your second fragment where you wanna hide the item):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO your code to hide item here
super.onCreateOptionsMenu(menu, inflater);
}
Similarly, for your fragment where you want to show that MenuItem you can do the similar thing.
In the fragment where you want to hide the Item
#Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.action_search);
item.setVisible(false);
and in onCreate() of your fragment
setHasOptionsMenu(true);
Adding to Muhammed's answer above. Once the item has been set as invisible, you may need to also disable the item. Note Google's comment: "Even if a menu item is not visible, it may still be invoked via its shortcut (to completely disable an item, set it to invisible and disabled)" under setVisible() in the MenuItem documentation.
Thus:
item.setVisible(false);
item.setEnabled (false);
Add below codes into your fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem item = menu.findItem(R.id.save);
item.setVisible(false);
}
// create Boolean variable in the main activity
private var menuvisibile: Boolean = true
// while navigating fragments set the menuvisibile value and use it
// variable as part of the return statement
invalidateOptionsMenu()
menuvisibile = false
override fun onCreateOptionsMenu(menu: Menu?): Boolean
{
val menuInflater = menuInflater
menuInflater.inflate(R.menu.notification,menu)
return menuvisibile
}
working well for me.
I have two fragment activities and one fragment. Here's how the app logic looks like:
FragmentActivity A ==> Fragment B ==> FragmentActivity C.
FragmentActivity A is the parent activity of fragment B and has an options menu that shows correctly.Fragment B contains a listview. When a list item is clicked on fragment B,its details are displayed in FragmentActivity C.Now i want to display an options menu inside C in the actionBar.However, the menu is only displayed after the menu button is clicked.I want it as an actionbar action.
Here is the code for Activity C:
public class LatestDetailsFragment extends FragmentActivity implements
OnItemClickListener {
public LatestDetailsFragment() {
photoImages = new ImageItem();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_latestdetails);
gallery.setOnItemClickListener(this);
// setHasOptionsMenu(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.details_fragment_menu, menu);
return super.onCreateOptionsMenu(menu);
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.contact:
ContactOwnerFragment contactFragment = new ContactOwnerFragment();
Bundle bundle = new Bundle();
bundle.putString(KEY_PHONE, phone);
contactFragment.setArguments(bundle);
contactFragment.show(getSupportFragmentManager(), "contact");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And the menu:
<menu 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"
tools:context="be.hcpl.android.example.MainActivity" >
<item
android:id="#+id/contact"
android:icon="#drawable/ic_action_call"
android:orderInCategory="100"
android:title="#string/contact"
app:showAsAction="ifRoom|withText">
</item>
I cannot use setHasOptionsMenu(true); on the activity because it raises an error,I don't know why. I want to display an icon on the actionbar.
You need to use menu.clear() before inflating menus.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.details_fragment_menu, menu);
return super.onCreateOptionsMenu(menu);
}
From the Documents
public abstract void clear () Remove all existing items from the menu, leaving it empty as if it had just been created.
This is definitely a noob question. I've followed the instructions here http://developer.android.com/guide/topics/ui/settings.html#Activity and when I click on settings, nothing happens.
Here's what I have in MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
}
Then I have a new java file called PrefsActivity.java
public class PrefsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
} }
Then I have res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="face_up"
android:title="#string/face_up"
android:summary="#string/face_up_desc"
android:defaultValue="false" />
</PreferenceScreen>
I am trying to make it compatible with minsdk 7 if possible. What am I missing?
You need to open your activity when you click on your settings button. If your using an action bar, use something like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
In your main Activity
// Ensure the right menu is setup
#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;
}
// Start your settings activity when a menu item is selected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
Intent settingsIntent = new Intent(this, PrefsActivity.class);
startActivity(settingsIntent);
}
return super.onOptionsItemSelected(item);
}