Make Static menu to dynamic from arraylist in android - java

I have a popup_menu.xml which has 3 item tags as static, so those 3 item values display in pop up menu, But I have one arraylist which has few values that I want to show in that popup menu.
Just I want to show carnames which is available in markersArray instead static Item values which is available in popup_menu.xml
Array List array
for(int i=0; i<markersArray.size(); i++){
String caname = markersArray.get(i).getCarname();
}
popup_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/one"
android:title="One"/>
<item
android:id="#+id/two"
android:title="Two"/>
<item
android:id="#+id/three"
android:title="Three"/>
</menu>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Click action
System.out.println("Float Icon Clicked");
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, fab);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.poupup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();//showing popup menu
}
});
}

Under this line of code
PopupMenu popup = new PopupMenu(MainActivity.this, fab);
Just itterate through your ArrayList and add it to the popup menu like this
for (String s : array) {
popup.getMenu().add(s);
}

Related

Pop up shows at the top

I have just created simple pop up with list items but when I click on Grid item it show the pop up at the top of the page like this all I need I want to show this pop up below the item grid
this is my onClick
gridView1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(getActivity(), gridView1);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(
getActivity(),
"You Clicked : " + item.getTitle(),
Toast.LENGTH_SHORT
).show();
return true;
}
});
popup.show(); //showing popup menu
return true;
}
});
this is my menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/newCheck"
android:title="New Check"/>
<item
android:id="#+id/settleCheck"
android:title="Settle Check"/>
<item
android:id="#+id/newGuestCheck"
android:title="New guest Check"/>
<item
android:id="#+id/discountCheck"
android:title="Discount Check"/>
<item
android:id="#+id/printCheck"
android:title="Print Check"/>
</menu>
You should change this line
PopupMenu popup = new PopupMenu(getActivity(), gridView1);
to this
PopupMenu popup = new PopupMenu(getActivity(), view);
so it will set the anchor for the menu to the proper element.

Unable to hide activity's options menu on some fragments

I am using options menu in an activity, in that I have inflated menu and onItemSelected for the menu item is done. And in fragment I am hiding the menu items which are not required to show on the fragment.
This is done well, I can see the desired menu items on the fragments. But on some fragments I dont want to show any menu item. So for this I tried to clear the menu, also I tried to setVisible false to all the items, also tried to setHasOptionsMenu(false); , But none is working. I can see all three menu items on that fragment.
Also I tried this answer: Hide/Show Action Bar Option Menu Item for different fragments
From Search merchants fragment in onPreparedOptionsMenu I did menu.setGroupVisible(R.id.main_menu_group, false);
Still not working.
Menu
<?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">
<group
android:id="#+id/main_menu_group">
<item
android:id="#+id/action_search"
android:orderInCategory="100"
android:title="customer"
app:showAsAction="always"
android:icon="#drawable/ic_search"/>
<item
android:id="#+id/action_create"
android:orderInCategory="100"
android:title="customer"
app:showAsAction="always"
android:icon="#drawable/ic_create"/>
<item
android:id="#+id/action_edit"
android:orderInCategory="100"
android:title="customer"
app:showAsAction="always"
android:icon="#drawable/ic_save"/>
</group>
</menu>
Home activity:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// menu.clear();
getMenuInflater().inflate(R.menu.menu_customer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create:
String favMerchantId = pref.getString("favMerchantId","");
String favKiranaName = pref.getString("favKiranaName","");
if(pref.getString("favMerchantId","").equals("null") && pref.getString("favKiranaName","").equals("null")){
CommonUtils.showAlert(HomeActivity.this,"There is no merchant yet.Please search for merchant.","No Merchant");
}
else {
FragmentManager fragmentManager = getSupportFragmentManager();
AddOrderFragment fragment1 = new AddOrderFragment();
Bundle bundle = new Bundle();
bundle.putString("kiranaName", favKiranaName);
bundle.putString("merchant_id", String.valueOf(favMerchantId));
bundle.putBoolean("ordersFrag", true);
fragment1.setArguments(bundle);
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.mycontainer, fragment1, "RETRIEVE_ADDORDER_FRAGMENT").addToBackStack("B").commit();
}
break;
case R.id.action_edit:
if (CommonUtils.isConnectedToInternet(HomeActivity.this)) {
if(AddOrderFragment.mOrderItemsList.isEmpty())
{
CommonUtils.showAlert(HomeActivity.this,getResources().getString(R.string.listAlert),"List");
// showAlert(getString(R.string.listAlert));
}
else {
Log.e("itemList", String.valueOf(AddOrderFragment.mOrderItemsList.size()));
Gson gson = new Gson();
String toServer = gson.toJson(
Collections.singletonMap("items", AddOrderFragment.mOrderItemsList)
);
String date_time = String.valueOf(CommonUtils.getCurrentDateTime());
new AddOrderAsyncTask(HomeActivity.this,AddOrderFragment.ordersFrag).execute(toServer,pref.getString("api_key",""), pref.getString("sessionUserId",""), AddOrderFragment.mMerchantId,date_time);
}
}
else {
// showAlert(getString(R.string.check_network));
CommonUtils.showAlert(HomeActivity.this,getResources().getString(R.string.check_network),"Check network");
}
break;
case R.id.action_search:
// go to search fragment
FragmentManager fragmentManager = HomeActivity.this.getSupportFragmentManager();
SearchMerchantFragment fragment1 = new SearchMerchantFragment();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.mycontainer, fragment1).addToBackStack("D").commit();
return true;
default:
break;
}
return true;
}
order's fragment to hide some menu items :
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem someMenuItem3 = menu.findItem(R.id.action_create);
someMenuItem3.setVisible(true);
// This does work
MenuItem someMenuItem = menu.findItem(R.id.action_search);
someMenuItem.setVisible(false);
MenuItem someMenuItem1 = menu.findItem(R.id.action_edit);
someMenuItem1.setVisible(false);
}
Search merchant fragment : In this I want to hide the menu, or all the menu items.
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem someMenuItem3 = menu.findItem(R.id.action_create);
someMenuItem3.setVisible(false);
// This does work
MenuItem someMenuItem = menu.findItem(R.id.action_search);
someMenuItem.setVisible(false);
MenuItem someMenuItem1 = menu.findItem(R.id.action_edit);
someMenuItem1.setVisible(false);
}
How can I hide this menu?
Please help.. Thank you..
you can try this,
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
}
and
setHasOptionsMenu(true); in onCreate of fragment.

How to create the mini dialogs (with pictures)

I've seen these dialogs around certain apps but I haven't been able to figure out how to show / create them. Am I missing something obvious? Thanks for your help!
You can create PopupMenu.
First create popup_menu.xml file in res/menu folder:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
tools:context=".MainActivity">
<item
android:id="#+id/action_copy"
android:orderInCategory="100"
android:title="#string/action_copy"/>
<item
android:id="#+id/action_forvard"
android:orderInCategory="110"
android:title="#string/action_forvard"/>
</menu>
Then implement PopupMenu inside onClick() method of onClickListener of your view:
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(MainActivity.this, view);
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_copy:
//your code here
break;
case R.id.action_forvard:
//your code here
break;
}
return true;
}
});
popup.show();
}

Popup context menu on ListView hold

I have a code sample got from the internet and the code goes like this
ListView lv1;
lv1 = (ListView) findViewById(R.id.custom_list);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
// print toast
}
});
Well I want to show context menu on list item click and I don't know how to do that.
You can use PopupMenu.
Create popup.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_action1"
android:icon="#drawable/menu_action1"
android:title="#string/menu_action1" />
...
</menu>
and add this to onItemClick:
PopupMenu popup = new PopupMenu(this, v);
// this = your activity
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.actions);
popup.show();
In addition your Activity should implements OnMenuItemClickListener so you can get menu click callback.

ActionBarSherlock menu ForceOverflow not showing

My problem is that when you open the app is not shown the overflow menu in the actionbar.
If you see en the MainActivity class I have a onOptionsItemSelected for the navigationdrawer, so when I create on the bottom a onCreatedOptionMenu with their respective onOptionsItemSelected fails.
and I dont know how to fix it.
This is what I want
Image
But nothing appears in the actionbar when I open application
This is my menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/Theme.Sherlock">
<item
android:id="#+id/more"
android:icon="#drawable/ic_action_overflow"
android:title="#string/more"
android:showAsAction="always"/>
<menu >
<item
android:id="#+id/contacto"
android:title="#string/contacto"
android:showAsAction="always|withText"/>
<item
android:id="#+id/recomenda"
android:title="#string/recomenda"
android:showAsAction="always|withText"/>
<item
android:id="#+id/salir"
android:title="#string/salir"
android:showAsAction="always|withText"/>
</menu>
MainActivity.java:
public class MainActivity extends SherlockFragmentActivity {
// Declare Variables
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
Fragment fragment0 = new Fragment0();
//20 more
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from drawer_main.xml
setContentView(R.layout.drawer_main);
// Get the Title
mTitle = mDrawerTitle = "¿Qué buscás?";
// Generate title
title = new String[] { " ASD ", "CORTE LÁSER", "CORTE METALES",
"CORTE POR CHORRO DE AGUA", "CURSOS", "EQUIPOS DE VIDEO", "FICHAS TÉCNICAS",
"FOTÓGRAFOS", "GRÁFICAS", "IMPRESIÓN 3D", "LIBRERÍAS Y PAPELERAS", "MAQUETAS Y PROTOTIPOS",
"MODELADO 3D", "MODELOS", "PLÁSTICOS", "ROUTER", "SUBLIMACIÓN", "TELGOPOR", "TERMOFORMADO",
"TORNERO MADERA", "TORNERO METALES", "VINILOS" };
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.listview_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass string arrays to MenuListAdapter
mMenuAdapter = new MenuListAdapter(MainActivity.this, title);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture listview menu item click
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
// Set the title on the action when drawer open
getSupportActionBar().setTitle(mDrawerTitle);
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// ListView click listener in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment0);
ft.addToBackStack(null);
break;
case 1:
ft.replace(R.id.content_frame, fragment1);
ft.addToBackStack(null);
break;
// and 19 more cases
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Get the title followed by the position
setTitle(title[position]);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
public boolean onCreatedOptionMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.menu1, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
And the Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
//...
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Sherlock.Light.ForceOverflow" >
<meta-data
//...
</application>
Please if you need some more information to answer, ask me
(I have not yet allowed to post images to show you my app)
Sorry if I made a mistake when posting, also for my English, I notice that I am beginner coding.
EDIT:
I think that solves the fact that the menu does not appear on the actionbar with this code and deleting the menu.xml:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu subMenu = menu.addSubMenu("Más");
subMenu.add("Volver");
subMenu.add("Contacto");
subMenu.add("Salir");
subMenu.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
And added this in the onOptionsItemSelected already have in the MainActivity.java:
if (item.getTitle().toString().equalsIgnoreCase("Publicá!")) {
Intent in = new Intent(getApplicationContext(),Publica.class);
startActivity(in);
Toast.makeText(this, "Publicá tu Negocio/Local/Emprendimiento", Toast.LENGTH_LONG).show();
} if (item.getTitle().toString().equalsIgnoreCase("Contacto")) {
Intent in = new Intent(getApplicationContext(),Contacto.class);
startActivity(in);
Toast.makeText(this, "Contactate y reportanos ...", Toast.LENGTH_LONG).show();
}
if (item.getTitle().toString().equalsIgnoreCase("Salir")) {
Intent i = new Intent(); i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i); android.os.Process.killProcess(android.os.Process.myPid());
Toast.makeText(this, "<-- Busca lo que necesitas", Toast.LENGTH_LONG).show();
}
Now i Have something like This
But not know to generate the menu on the actionbar be an icon instead of text like "Type".
That is my problem now.
This is what you need to do with the item tags
android:showAsAction=["ifRoom" | "never" | "withText" | "always" | "collapseActionView"]
always will always show you menus, never will let your menu item to come in the overflow mode..
set
android:showAsAction="never"
look here for more description.

Categories