I am using options menu in message fragment where I can add friends from menu. I can navigate to this fragment from activity or fragment. When I launch this message fragment, menu is working fine. When I do navigate through other screen and come to message fragment menu disappears. After using/navigating in the application for 4-5 minutes, menu starts behaving randomly.
Strange behavior is, when I do launch message fragment from activity, menu always works well. This behaves randomly when I launch it from fragment.
Here is my code
public class MessagesFragment extends BaseFragment{
private static final String TAG = MessagesFragment.class.getSimpleName();
Context mContext;
View mView;
private ListView listBuddy;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
((InnerActivity)getActivity()).setActionbarTitle(getResources().getString(R.string.my_buddies));
View v = inflater.inflate(R.layout.fragment_messages, container, false);
listBuddy = (ListView) v.findViewById(R.id.listViewFindBuddy);
this.mView = v;
return v;
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
// TODO Auto-generated method stub
super.setUserVisibleHint(isVisibleToUser);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.messages, menu);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_add:
break;
}
return super.onOptionsItemSelected(item);
}
Activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
add the following code in your activity :
#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;
}
Related
I am trying to invoke optionMenu from ImageButton in onClick listener but getting following exception.
07-19 01:08:09.693: E/AndroidRuntime(15133): java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.getItem(int)' on a null object reference
public class myApp extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
}
/** Called when the activity is first created. */
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
menu_icon = (ImageView) findViewById(R.id.icon);
infoBtn = (ImageButton) findViewById(R.id.pfkey_button);
menu_icon.setImageResource(R.drawable.info_icon);
menu_icon.setOnClickListener(this);
infoBtn.setOnClickListener(this);
//Create Terminal View
terminalView = (TerminalView)findViewById(R.id.terminalView);//new TerminalView(this);
registerForContextMenu(terminalView);
}
public void onClick(View v) {
KeyEvent event = null;
if (v == infoBtn) {
openOptionsMenu();
}
if (v == menu_icon) {
openOptionsMenu();
}
}
}
I also tried with `infoBtn = (ImageButton)myApp.this.findViewById(R.id.pfkey_button); but not working
I don't know why you overrided onPostCreate,I think you shold do those things in onCreate.
Apart from this, openOptionsMenu not work in my app.
So I use a ToolBar to replace the ActionBar.Here is the code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mToolbar.showOverflowMenu();
}
});
}
// override this method to inflat the menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected: "+item.getTitle().toString());
return super.onOptionsItemSelected(item);
}
}
Make sure to inflate your menu first inside onCreateOptionsMenu()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the navigation_menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.your_menu, menu);
return true;
}
It is possible that your menu itself is not inflated, thus causing the exception. Please provide the full code if this is not the case
here it was crashing although implementation is correct.
#Override
public boolean onMenuOpened(int featureId, Menu menu) {
/*if (!hostcom.isConnected())
menu.getItem(0).setTitle("Login");
else
menu.getItem(0).setTitle("Logout");*/
return true;
}
I have an ActionBarActivity and one Fragment. The Activity has no menu inflated, while the Fragment has a menu with two buttons. Fragment menu is visible, but the buttons don't react at all when tapped. At debugging I can see that both onCreateOptionsMenu() for Fragment and Activity get called, but when tapping buttons no onOptionsItemSelected() gets called, neither from Activity nor from Fragment.
Activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
Fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainActivity = (NavigationActivity)getActivity();
setHasOptionsMenu(true);
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState){
return (ScrollView) inflater.inflate(R.layout.tutoring_detail, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.query_details_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.accept_query:
respondToQuery(true);
return true;
case R.id.decline_query:
respondToQuery(false);
return true;
default:
break;
}
return false;
}
Menu to be displayed in Fragment
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
<item
android:id="#+id/accept_query"
android:orderInCategory="100"
app:showAsAction="always"
android:checkable="true"
style="?android:attr/borderlessButtonStyle"
app:actionViewClass="android.widget.ImageButton"/>
<item
android:id="#+id/decline_query"
android:orderInCategory="101"
app:showAsAction="always"
android:checkable="true"
style="?android:attr/borderlessButtonStyle"
app:actionViewClass="android.widget.ImageButton"/>
</menu>
In the Activity class,
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
return false;
}
In the Fragment,
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(getActivity(), "called " + item.getItemId(), Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
You must use super.onOptionsItemSelected(item) in the parent activity's onOptionsItemSelected(...) method.
From Activity | Android Developers:
Derived classes should call through to the base class for it to perform the default menu handling.
Try moving setHasOptionsMenu(true) inside of the onCreateView() method in your Fragment instead of onCreate().
I had a similar issue after making special layout for my action button (I made an Image Button and needed to pad it and change some other things so I had to use layout for it).
Then onOptionsItemSelected lost connection with this imageButton so I just use clickListener for it inside onCreateOptionsMenu. It might not be the best practice, maybe there is a better solution, but this is what solve my problem.
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.picker_list_menu, menu);
MenuItem itemDone = menu.findItem(R.id.menu_done);
MenuItemCompat.setActionView(itemDone, R.layout.menu_layout_done);
menuDoneIB = (ImageButton) MenuItemCompat.getActionView(itemDone);
itemDone.getActionView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your code..
}
});
}
Try using oncreateview
public static class ExampleFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);
}
}
If you have dynamically changed menu item, for instance, a badge menu (https://stackoverflow.com/a/16648170/2914140 or https://stackoverflow.com/a/26017587/2914140), you should initialize the item in onCreateOptionsMenu and re-set setOnClickListeners after every change of the item.
In my case:
private MenuItem menuItem;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_catalog, menu);
menuItem = menu.findItem(R.id.action_badge);
writeBadge(0);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_badge) {
// Your code.
return true;
}
return super.onOptionsItemSelected(item);
}
private void writeBadge(int count) {
MenuItemCompat.setActionView(menuItem, R.layout.item_badge);
RelativeLayout layout = (RelativeLayout) MenuItemCompat.getActionView(menuItem);
// A TextView with number.
TextView tv = (TextView) layout.findViewById(R.id.badge);
if (count == 0) {
tv.setVisibility(View.INVISIBLE);
} else {
tv.setVisibility(View.VISIBLE);
tv.setText(String.valueOf(count));
}
// An icon, it also must be clicked.
ImageView imageView = (ImageView) layout.findViewById(R.id.image);
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(menuItem);
}
};
menuItem.getActionView().setOnClickListener(onClickListener);
imageView.setOnClickListener(onClickListener);
}
I am passing the click event to fragment from the activity. This worked for me.
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
return getSupportFragmentManager().getFragments().get(getSupportFragmentManager().getFragments().size() - 1)
.onOptionsItemSelected(item);
}
how to save the text given to edit text, after clicking the save action button in action bar that should save to another activity.
my first activity Add.java
public class Add extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
getActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflate=getMenuInflater();
getMenuInflater().inflate(R.menu.activity_add_action, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:save();
return true;
case R.id.cancel:cancelnavi();
return true;
}
return super.onOptionsItemSelected(item);
}
private void save() {
EditText titlename;
titlename=(EditText)findViewById(R.id.edittitle);
String title=titlename.getText().toString();
if (title.equalsIgnoreCase("")){
Toast.makeText(Add.this, "Script title should not be empty", Toast.LENGTH_LONG).show();
} else {
Intent i;
i=new Intent(getApplicationContext(), Scripts.class);
i.putExtra("n", titlename.getText().toString());
startActivityForResult(i, 0);
titlename.setText("");
}
}
}
It should be saved to scripts.java
public class Scripts extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scripts);
getActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflate=getMenuInflater();
getMenuInflater().inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:editscript();
break;
}
return true;
}
private void editscript() {
Intent editinIntent;
editinIntent=new Intent(Scripts.this, Edit.class);
startActivity(editinIntent);
}
}
Maybe this can help you.
public class Scripts extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scripts);
getActionBar().setDisplayShowHomeEnabled(false);
//Extract the data
String yourTitle = getIntent().getStringExtra("n");
}
}
I created a simple project that Button in Activity click to Show Toast from Fragment.Works fine when just click Button, but after orientation changed and clicking Button occurs error.
public class MainActivity extends Activity {
PlaceholderFragment pf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pf = new PlaceholderFragment();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
pf.showToast();
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, pf)
.commit();
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Log.i("TAG", "onCreateView");
return rootView;
}
public void showToast(){
Toast.makeText(getActivity(), "Show Toast from PlaceholderFragment", Toast.LENGTH_SHORT).show();
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Log.i("TAG", "onAttach");
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Log.i("TAG", "onDetach");
}
}
}
I found out Fragment was calling onAttach and onDetach after orientating. How can i fix this problem?
When the device Orientation changes, the activity in which the fragment sits is by default destroyed and created again. You can avoid these changes by adjusting the android:configChanges in the manifest file. This code should work:
android:configChanges="keyboardHidden|orientation"
I have one problem using ActivityGroup. I have two activities inside an ActivityGroup and both of them use a menu (overriding the onCreateOptionMenu and onOptionsItemSelected).
Both activity have different menus.
Well, the problem is that the second activity always show the first activity menu,
Any idea about this issue?
Below is my code
public class myActivityGroup extends ActivityGroup {
----
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mIdList.add(Id);
View view = window.getDecorView();
history.add(view);
setContentView(view);
}
}
public void back() {
if (history.size() > 0) {
int lastActivityIndex = history.size() - 1;
int lastIDIndex = mIdList.size() - 1;
String activityId = mIdList.get(lastIDIndex);
Log.d(TAG, "activityId:" + activityId);
history.remove(lastActivityIndex);
mIdList.remove(lastIDIndex);
setContentView(history.get(history.size() - 1));
} else {
finish();
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Activity current = getLocalActivityManager().getCurrentActivity();
return current.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
LocalActivityManager manager = getLocalActivityManager();
Activity current = manager.getCurrentActivity();
return current.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
LocalActivityManager manager = getLocalActivityManager();
Activity current = manager.getCurrentActivity();
return current.onOptionsItemSelected(item);
}
}
public class ChildActivity1 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//add menu here
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle on menu item selected here
return true;
}
}
public class ChildActivity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//add menu here
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.offer_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle on menu item selected here
return true;
}
}
When you add the activities, the "current" activity is that last one added. I suspect that if you interact with the other activity then activate the options menu it will work.
Try retrieving the activity you need using the String Id:
LocalActivityManager manager = getLocalActivityManager();
Activity a = manager.getActivity(id);
return a.onCreateOptionsMenu(menu);