I am trying create a menu list dynamically, i was able to create the menu option but every time i run my code the icon for the main item disappear: here is my code sample:
private static final int SUB_Menu_ONE = R.menu.settings;
private static final int SUB_Menu_TWO = R.menu.settings + 1;
private static final int SUB_Menu_THREE= R.menu.settings + 2;
private static final int SUB_Menu_FOUR = R.menu.settings + 3;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings, menu);
return true;
}
// private Menu menu;
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
menu.add(0, SUB_Menu_ONE, Menu.NONE, "Sub Menu Item 0");
menu.add(0, SUB_Menu_TWO, Menu.NONE, "Sub Menu Item 1");
menu.add(0, SUB_Menu_THREE, Menu.NONE, "Sub Menu Item 2");
menu.add(0, SUB_Menu_FOUR, Menu.NONE, "Sub Menu Item 3");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent inent;
switch (item.getItemId()) {
case SUB_Menu_ONE:
// doStuff();
break;
case SUB_Menu_TWO:
// doStuff();
break;
case SUB_Menu_THREE:
// doStuff();
break;
case SUB_Menu_FOUR:
// doStuff();
break;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
return false;
}
Here is my XML Layout for Menu settings
<?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:compat="http://schemas.android.com/tools">
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings_title"
android:icon="#drawable/cuslistticketbutton"
app:showAsAction="always|withText"
android:actionLayout="#layout/custabview"
compat:showAsAction="ifRoom"
>
<!--<menu>-->
<!--<item-->
<!--android:id="#+id/menu_addticket"-->
<!--android:showAsAction="never"-->
<!--android:icon="#drawable/add_tickets"-->
<!--android:title=""-->
<!--compat:ignore="AppCompatResource,HardcodedText" />-->
<!--</menu>-->
</item>
</menu>
Any help is welcome
You have to set the icon programmatically.
menu.add(0, SUB_Menu_ONE, Menu.NONE, "PREMIUM (Live Video & Audio)").setIcon(R.drawable.icon);
Related
I have a menu item system implemented into my action bar, I am trying to get a menu item to become invisible once clicked and then to become visible again after clicking a different menu item.
The reason for this is to prevent a menu item getting clicked more than once.
I have done the following attempt below however, I get a null pointer exception error. I believe I may need to implement some if statements here but I'm not sure how to go about it.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.tasklistmenu,menu);
return true;
}//OnCreateOptionsMenu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.allTasks:
item.setVisible(false);
MenuItem notStartedStatus = findViewById(R.id.notStartedStatus);
notStartedStatus.setVisible(true);
MenuItem inProgressStatus = findViewById(R.id.inProgressStatus);
inProgressStatus.setVisible(true);
MenuItem completeStatus = findViewById(R.id.completeStatus);
completeStatus.setVisible(true);
Log error
Attempt to invoke interface method 'android.view.MenuItem
android.view.MenuItem.setVisible(boolean)' on a null object reference
NEW CODE
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem allTasks = menu.findItem(R.id.allTasks);
MenuItem notStartedStatus = menu.findItem(R.id.notStartedStatus);
MenuItem completeStatus = menu.findItem(R.id.completeStatus);
MenuItem inProgressStatus = menu.findItem(R.id.inProgressStatus);
if(tasksIsVisible) {
allTasks.setVisible(true);
} else {
allTasks.setVisible(false);
}
if(notStartedIsVisible) {
notStartedStatus.setVisible(true);
} else {
notStartedStatus.setVisible(false);
}
if(completeIsVisible) {
completeStatus.setVisible(true);
} else {
completeStatus.setVisible(false);
}
if(inProgressIsVisible) {
inProgressStatus.setVisible(true);
} else {
inProgressStatus.setVisible(false);
}
return true;
}//OnPrepareOptions
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.allTasks:
tasksIsVisible = false;
invalidateOptionsMenu();
Its not enough to change the isVisible variable. You have to call the setVisible() method every time you want to change the visibility. That method does more than just setting a boolean value, so just changing a boolean value will not do.
After changing the isVisible value to false, you need to call invalidateOptionsMenu() which will re-launch the menu by calling onPrepareOptionsMenu() again.
public boolean onPrepareOptionsMenu(Menu menu)
{
MenuItem notStartedStatus = menu.findItem(R.id.notStartedStatus);
if(isVisible)
{
notStartedStatus.setVisible(true);
}
else
{
notStartedStatus.setVisible(false);
}
return true;
}
Try this code for making the menu items unvisible:
...
isVisible = false;
invalidateOptionsMenu();
...
I will create an app that user will be enter the website url to my app. Then I am showing this page in my app using WebView.
As you know, when user clicks the any text in the context a little bit long, android cursor will appear then we can select text as many as we want.
After selection, we will see that "COPY, SHARE, SELECT ALL" etc..
My question is that when user selects text, I want to show them different options. Let's say "MyCOPY, SendTwitter, SendMessage".
How can i do that?
What I did so far?
I am just creating bar at the top of the app. But I don't want this.
Here is the code:
private WebView view;
private final String TAG = MainActivity.class.getSimpleName();
private ActionMode actionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.view = findViewById(R.id.webView);
view.loadUrl("https://stackoverflow.com/questions/28385768/android-how-to-check-for-successful-load-of-url-when-using-webview-loadurl");
view.setWebViewClient(new MyWebViewClient());
Log.d(TAG, view.getUrl());
view.setOnLongClickListener((v) -> {
if (actionMode != null)
return false;
actionMode = startSupportActionMode(actionCallBack);
return true;
});
}
Where startSupportActionMode(actionCallBack) is
private ActionMode.Callback actionCallBack = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.custommenu, menu);
actionMode.setTitle("Choose");
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.example_item_1:
Toast.makeText(MainActivity.this, "Option 1 selected", Toast.LENGTH_SHORT).show();
actionMode.finish();
return true;
case R.id.example_item_2 :
Toast.makeText(MainActivity.this, "Option 2 selected", Toast.LENGTH_SHORT).show();
actionMode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
actionMode = null;
}
};
You can implement the ActionMode.Callback interface to create your own menu upon selection.
An action mode's lifecycle is as follows:
onCreateActionMode(ActionMode, Menu) once on initial creation
onPrepareActionMode(ActionMode, Menu) after creation and any time the
ActionMode is invalidated
onActionItemClicked(ActionMode, MenuItem)
any time a contextual action button is clicked
onDestroyActionMode(ActionMode) when the action mode is closed
just make sure that your text views allow for text selection (android:textIsSelectable="true")
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_share:
shareCurrentItem();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
// Called when the user exits the action mode
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
then call startActionMode() to enable the contextual action mode when appropriate (source), such as inside a setOnLongClickListener
I have a menu resource file like this :
<menu xmlns:android="http://schemas.android.com/apk/res/android"
>
<group android:checkableBehavior="single">
<item android:id="#+id/sort_all"
android:title="All"
android:orderInCategory="1" />
<item android:id="#+id/sort_co"
android:title="CoAuthors"
android:orderInCategory="2" />
<item
android:id="#+id/sort_title"
android:title="Title"
android:orderInCategory="3" />
<item
android:id="#+id/sort_journal"
android:title="Journals"
android:orderInCategory="4" />
<item
android:id="#+id/sort_year"
android:title="Year"
android:orderInCategory="5" />
</group>
</menu>
and I'm using it on a popup menu :
final PopupMenu popup = new PopupMenu(MainActivity.this, btn1);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.search_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.sort_co:
popup.getMenu().findItem(item.getItemId()).setChecked(true);
return true;
case R.id.sort_title:
item.setChecked(true);
return true;
case R.id.sort_journal:
item.setChecked(true);
return true;
case R.id.sort_year:
item.setChecked(true);
return true;
case R.id.sort_all:
item.setChecked(true);
return true;
default:
return true;
}
}
});
popup.show();
}
});
as you can see i have tried using
item.setChecked(true) and
popup.getMenu().findItem(item.getItemId()).setChecked(true);
but the problem is when i click on items just before closing menu, item gets checked but when i reopen the menu again, it is not checked !
I've also tried using
MenuItem subMenuItem = item.getSubMenu().getItem(INDEX_OF_ITEM);
subMenuItem.setChecked(!subMenuItem.isChecked());
but it gives me NullPointerException... .
You can try this modification in you code. Like this:
final PopupMenu popup = new PopupMenu(MainActivity.this, btn1);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.search_menu, popup.getMenu());
int item_selected = 1;
if(item_selected == 1){
popup.getMenu().findItem(R.id.sort_co).setChecked(true);
}else if(item_selected == 2) {
popup.getMenu().findItem(R.id.sort_title).setChecked(true);
}
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.sort_co:
item.setChecked(true);
item_selected = 1;
return true;
case R.id.sort_title:
item.setChecked(true);
item_selected = 2;
return true;
default:
return true;
}
}
});
popup.show();
I have implemented the Android search widget in my navigation drawer based app. I have set it to open the keyboard and focus the editText when clicking on the search icon. I want to set the back button (up button) to hide the keyboard. I have searched the web for the R.id of the up button, and found this android.R.id.home. So I have set it to be:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
...
case android.R.id.home:
hideKeyboard();
break;
...
}
I debugged the code and noticed that clicking on the navigation bar icon fires up the android.R.id.home, but hitting the up button of the search widget doesn't even enter the onOptionsItemSelected(MenuItem item) function.
I have also tried this:
searchView.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard();
}
}
});
But didn't work.
How can I hide the keyboard when pressing the back (up) button?
Setting the search view:
private void setSearchView(Menu menu) {
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
Home.getFilter().filter(newText);
return true;
}
public boolean onQueryTextSubmit(String query) {
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
}
The following code should work:
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setOnCloseListener(new OnCloseListener() {
#Override
public bool OnClose() {
searchView.clearFocus();
return true;
});
However this didn't work for me for some reason. :-/
I found the workaround below here:
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
#Override
public void onViewDetachedFromWindow(View v) {
searchView.clearFocus();
}
#Override
public void onViewAttachedToWindow(View v) {
}
});
I don't think that using android.R.id.home will work since I think that onOptionsItemSelected(android.R.id.home) will only be called once the SearchView has been closed.
I have a menu.java and in this file I have lines of codes to allow the user to press the menu button and "MENU1" and "MENU2" will appear on their android phone. However, I have multiple java classes, and each java classes is its own activity. What would I need to do to have this menu class function in each activity without putting every line of code in the menu.java into each other .java
This is my Menu.java
public class Menu extends Activity {
public boolean onCreateOptionsMenu(android.view.Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater a = getMenuInflater();
a.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.MENU1:
startActivity(new Intent("com.helloworld.test.MENU1"));
return true;
case R.id.MENU2:
startActivity(new Intent("com.helloworld.test.MENU2"));
return true;
}
return false;
}
}
You could create a base activity that all your other activities extend:
public class BaseActivity extends Activity {
public boolean onCreateOptionsMenu(android.view.Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater a = getMenuInflater();
a.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.MENU1:
startActivity(new Intent("com.helloworld.test.MENU1"));
return true;
case R.id.MENU2:
startActivity(new Intent("com.helloworld.test.MENU2"));
return true;
}
return false;
}
}