How do I do a custom dropdown/popup menu anchored to a button?
I need it to work like the popup menu (anchored to a view), and do something when I click an item from the menu.
How do I add items to the menu by code, keeping menu's height and make it scrollable if there are more than 5 items. I don't need to add any images, just text.
Update: To create a popup menu in android with Kotlin refer my answer here.
To create a popup menu in android with Java:
Create a layout file activity_main.xml under res/layout directory which contains only one button.
Filename: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="62dp"
android:layout_marginTop="50dp"
android:text="Show Popup" />
</RelativeLayout>
Create a file popup_menu.xml under res/menu directory
It contains three items as shown below.
Filename: poupup_menu.xml
<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 class which displays the popup menu on button click.
Filename: MainActivity.java
public class MainActivity extends Activity {
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.popup_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
}
}); //closing the setOnClickListener method
}
}
To add programmatically:
PopupMenu menu = new PopupMenu(this, view);
menu.getMenu().add("One");
menu.getMenu().add("Two");
menu.getMenu().add("Three");
menu.show();
Follow this link for creating menu programmatically.
I know this is an old question, but I've found another answer that worked better for me and it doesn't seem to appear in any of the answers.
Create a layout xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dip"
android:paddingBottom="5dip"
android:paddingStart="10dip"
android:paddingEnd="10dip">
<ImageView
android:id="#+id/shoe_select_icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center_vertical"
android:scaleType="fitXY" />
<TextView
android:id="#+id/shoe_select_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20sp"
android:paddingStart="10dp"
android:paddingEnd="10dp"/>
</LinearLayout>
Create a ListPopupWindow and a map with the content:
ListPopupWindow popupWindow;
List<HashMap<String, Object>> data = new ArrayList<>();
HashMap<String, Object> map = new HashMap<>();
map.put(TITLE, getString(R.string.left));
map.put(ICON, R.drawable.left);
data.add(map);
map = new HashMap<>();
map.put(TITLE, getString(R.string.right));
map.put(ICON, R.drawable.right);
data.add(map);
Then on click, display the menu using this function:
private void showListMenu(final View anchor) {
popupWindow = new ListPopupWindow(this);
ListAdapter adapter = new SimpleAdapter(
this,
data,
R.layout.shoe_select,
new String[] {TITLE, ICON}, // These are just the keys that the data uses (constant strings)
new int[] {R.id.shoe_select_text, R.id.shoe_select_icon}); // The view ids to map the data to
popupWindow.setAnchorView(anchor);
popupWindow.setAdapter(adapter);
popupWindow.setWidth(400);
popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
devicesAdapter.setSelectedLeftPosition(devicesList.getChildAdapterPosition(anchor));
break;
case 1:
devicesAdapter.setSelectedRightPosition(devicesList.getChildAdapterPosition(anchor));
break;
default:
break;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
devicesAdapter.notifyDataSetChanged();
}
});
popupWindow.dismiss();
}
});
popupWindow.show();
}
The Kotlin Way
fun showPopupMenu(view: View) {
PopupMenu(view.context, view).apply {
menuInflater.inflate(R.menu.popup_men, menu)
setOnMenuItemClickListener { item ->
Toast.makeText(view.context, "You Clicked : " + item.title, Toast.LENGTH_SHORT).show()
true
}
}.show()
}
UPDATE: In the above code, the apply function returns this which is not required, so we can use run which don't return anything and to make it even simpler we can also remove the curly braces of showPopupMenu method.
Even Simpler:
fun showPopupMenu(view: View) = PopupMenu(view.context, view).run {
menuInflater.inflate(R.menu.popup_men, menu)
setOnMenuItemClickListener { item ->
Toast.makeText(view.context, "You Clicked : ${item.title}", Toast.LENGTH_SHORT).show()
true
}
show()
}
First, create a folder named “menu” in the “res” folder.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/search"
android:icon="#android:drawable/ic_menu_search"
android:title="Search"/>
<item
android:id="#+id/add"
android:icon="#android:drawable/ic_menu_add"
android:title="Add"/>
<item
android:id="#+id/edit"
android:icon="#android:drawable/ic_menu_edit"
android:title="Edit">
<menu>
<item
android:id="#+id/share"
android:icon="#android:drawable/ic_menu_share"
android:title="Share"/>
</menu>
</item>
</menu>
Then, create your Activity Class:
public class PopupMenu1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_menu_1);
}
public void onPopupButtonClick(View button) {
PopupMenu popup = new PopupMenu(this, button);
popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(PopupMenu1.this,
"Clicked popup menu item " + item.getTitle(),
Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
}
Related
I want to customize the popupmenu in android, default popup menu gives more space ,so I'm trying to change the custom layout in popup menu but I cant figure out how.
Note: I want to do this small popup design so I go with default popup menu but i want to customize it.
findViewById(R.id.menuclick).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popupMenu = new PopupMenu(Sample1.this, view);
popupMenu.setOnMenuItemClickListener(Sample1.this);
popupMenu.inflate(R.layout.menus_layout);
popupMenu.show();
}
});
To inflate popupMenu from a button onClick, use the following code.
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainActivity.this, v);
popup.getMenuInflater().inflate(R.menu.pop_up, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this, "Some Text" + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();//showing popup menu
}
});
EDIT
To style the popupMenu, add the following style.
<style name="PopupMenu" parent="#android:style/Widget.PopupMenu">
<item name="android:popupBackground">#ffffff</item>
</style>
I noticed you also want to add icons next to your text. It is possible to add icons in popupMenu. However it is a better approach to use popup Window instead. Here is a sample code:
PopupWindow mypopupWindow;
setPopUpWindow();
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mypopupWindow.showAsDropDown(v,-153,0);
//showAsDropDown(below which view you want to show as dropdown,horizontal position, vertical position)
}
}
});
}
private void setPopUpWindow() {
LayoutInflater inflater = (LayoutInflater)
getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.popup, null);
Start=(RelativeLayout)view.findViewById(R.id.start_btn);
Pause=(RelativeLayout)view.findViewById(R.id.pause_btn);
Stop=(RelativeLayout)view.findViewById(R.id.stop_btn);
mypopupWindow = new PopupWindow(view,300, RelativeLayout.LayoutParams.WRAP_CONTENT, true);
popup Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:background="#drawable/whitedrawable"
android:paddingRight="0dp"
android:layout_marginRight="0dp"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/startimg"
android:id="#+id/startimg"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
/>
<TextView
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="0dp"
android:text="Start"
android:layout_toRightOf="#+id/startimg"
/>
<!-- Continue for other items-->
The whitedrawable can be used to set a background of your choice. You can use 9patch to get the shadow and rounded corners for the background.
To dismiss the popupWindow, use the following code:
mypopupWindow.getContentView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mypopupWindow.dismiss();
}
});
To dismiss using the back button, use:
#Override
public void onBackPressed() {
if(mypopupWindow.isShowing()) {
mypopupWindow.dismiss();
return;
}
super.onBackPressed();
}
My answer will be like an update for this answer (the first answer in this post) focusing at PopupWindow using Kotlin, also using View Binding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val bind = ViewBinding.inflate(inflater, container, false)
val popupInflater =
requireActivity().applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflaterERVICE) as LayoutInflater
val popupBind = YourPopupLayoutBinding.inflate(popupInflater)
popupBind.icon1.setOnClickListener { // do your thing for 1st icon }
popupBind.icon2.setOnClickListener { // do your thing for 2nd icon }
val popupWindow = PopupWindow(
popupBind.root, 126.fromDpToPx.toInt(),
89.fromDpToPx.toInt(), true
).apply { contentView.setOnClickListener { dismiss() } }
// make sure you use number than wrap_content or match_parent,
// because for me it is not showing anything if I set it to wrap_content from ConstraintLayout.LayoutParams.
bind.yourButton.setOnClickListener(popupWindow::showAsDropDown)
return bind.root
}
This code is in Fragment class, that's why I call applicationContext using requireActivity()
Here is the code for layout,
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="126dp"
android:layout_height="89dp"
android:background="#FFFFFF">
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/icon1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:drawablePadding="8dp"
android:paddingHorizontal="10dp"
android:paddingVertical="10dp"
android:text="#string/tokopedia"
android:textColor="#color/dark_grey"
app:drawableStartCompat="#drawable/ic_icon1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/icon2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:drawablePadding="8dp"
android:paddingHorizontal="10dp"
android:paddingVertical="10dp"
android:text="#string/shopee"
android:textColor="#color/dark_grey"
app:drawableStartCompat="#drawable/ic_icon2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/icon1" />
</androidx.constraintlayout.widget.ConstraintLayout>
Don't forget to add background color in custom layout, also you can styling freely in custom layout.
Hope this can help you all :)
My problem is that I want to achieve a display in which on clicking the dotted button on side of every song I want a display to pop up like in the second image shown below?
To create POPUp menu on button click:
list_item.xml:
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="62dp"
android:layout_marginTop="50dp"
android:text="Show Popup" />
It contains three items as show below. It is created inside the res/menu directory. File: poupup_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/one"
android:title="PlayNext"/>
<item
android:id="#+id/two"
android:title="AddtoPlayList"/>
<item
android:id="#+id/three"
android:title="Add to Queue"/>
</menu>
It displays the popup menu on button click. File: MainActivity.java
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.popup_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
}
}); //closing the setOnClickListener method
}
I have an EditText and its text gets selected from through code. But I want to allow users to cut/copy the selected text. However, the cut/copy context menu doesn't appear until user long presses on text. But then it loses the actual selection. So, I'm thinking to show the context menu as the text get selected by the code.
I tried this inside onFocusChanged, but nothing appeared.
openContextMenu(EditText);
IF I follow you usecase correctly, you can open context menu from the onFocusChangeListener registered on the testedEditText.
I prepared some small test for that which seems to be correctly supporting your usecase.
You need to openMenu on the hooks which are selecting the content in the EditText.
public class Main extends Activity {
private EditText testedEditText;
private Button selectingButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selectingButton = (Button) findViewById(R.id.button);
testedEditText = (EditText) findViewById(R.id.textView);
registerForContextMenu(testedEditText);
selectingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
testedEditText.setSelection(6, 11);
openContextMenu(testedEditText);
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.cmenu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.select_all:
return true;
case R.id.copy:
//do something
return true;
case R.id.cut:
//do something
return true;
case R.id.paste:
//do something
return true;
default:
return super.onContextItemSelected(item);
}
}
}
Weirdly enough registering testedEditText.requestFocus(), and setting onFocusChangedListener for EditText was not enough.
Additional xml files for reference:
cmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/select_all"
android:title="select all"
/>
<item android:id="#+id/copy"
android:title="copy"
/>
<item android:id="#+id/cut"
android:title="cut"
/>
<item android:id="#+id/paste"
android:title="paste"
/>
</menu>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World, Initial Text..."
android:layout_centerInParent="true"
/>
<Button android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="button"
/>
</RelativeLayout>
i would like to implement a popup menu similar to google's play store as shown below.
so basically from what i understand, i'll need an activity and a layout for this activity with a listview defined in it. i need to create my custom adapter. also, i need to create a list layout would contain the information and a view (with the 3 dots) that will serve as the button to launch the popup menu? the issue that i'm seeing here is that how do i create a listener for this view only and how do i reference the value for that specific list item in the list view.
i don't have any code available yet as i haven't started anything related to this. i'm currently getting info in theory for now but if required i will create a sample code.
thanks.
Using popup menu it's quite simple to create a menu with these three steps:
1 - Add a click listener to the menu button using OnClickListener or as i prefer from the layout xml:
<ImageButton android:id="#+id/menu_button" android:onClick="showMenu" ... />
2 - Create the menu layout menu_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/item_settings"
android:showAsAction="ifRoom|withText"
android:title="Settings"
android:visible="true"/>
<item
android:id="#+id/item_about"
android:showAsAction="ifRoom|withText"
android:title="About"
android:visible="true"/>
</menu>
3 - Create a popup menu, inflate the xml layout and show it:
public void showMenu (View view)
{
PopupMenu menu = new PopupMenu (this, view);
menu.setOnMenuItemClickListener (new PopupMenu.OnMenuItemClickListener ()
{
#Override
public boolean onMenuItemClick (MenuItem item)
{
int id = item.getItemId();
switch (id)
{
case R.id.item_settings: Log.i (Tag, "settings"); break;
case R.id.item_about: Log.i (Tag, "about"); break;
}
return true;
}
});
menu.inflate (R.menu.menu_layout);
menu.show();
}
ActionBarCompat List PopupMenu implementation is here (with back port available because it uses ABC)!
You can also get this sample from Github or from SDK (Mr.Morgan commented below)
/sdk/samples/android-19/ui/ActionBarCompat-ListPopupMenu. Make sure to
install Samples for SDK under Android 4.4.2 (API 19)
You can use like this:
public class MainActivity extends Activity {
ListView listView_Actions;
ArrayList<String> actionsArrayList;
Button btn_ViewPopUp;
ArrayAdapter<String> actionsAdapter;
static final int CUSTOM_DIALOG_ID1 = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_ViewPopUp=(Button) findViewById(R.id.btn_ViewPopUp);
actionsArrayList=new ArrayList<String>();
actionsArrayList.add("Action 1");
actionsArrayList.add("Action 2");
}
#Override
protected void onStart() {
super.onStart();
btn_ViewPopUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(CUSTOM_DIALOG_ID1);
actionsAdapter = new MyCustomBaseAdapter(getApplicationContext(), R.layout.list_actions, actionsArrayList);
listView_Actions.setAdapter(actionsAdapter);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case CUSTOM_DIALOG_ID1:
dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.list_actions);
listView_Actions = (ListView) dialog.findViewById(R.id.listView_Actions);
break;
}
return dialog;
}
class MyCustomBaseAdapter extends ArrayAdapter<String>
{
public MyCustomBaseAdapter(Context context, int textViewResourceId, ArrayList<String> actionsArrayList) {
super(context, textViewResourceId,actionsArrayList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.action_list_cell, null);
final TextView lblContactAction;
lblContactAction = (TextView) v.findViewById(R.id.txtContactAction);
lblContactAction.append(actionsArrayList.get(position));
return v;
}
}
}
Now XML files:
action_list_cell.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/background_light" >
<TextView
android:id="#+id/txtContactAction"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="18dp"
android:textColor="#android:color/black" />
</LinearLayout>
list_actions.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/rounded_corner_top">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#DB6A16"
android:orientation="vertical"
android:paddingBottom="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp" >
<ListView
android:id="#+id/listView_Actions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff" >
</ListView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
first of all you need to make your custom adapter with a view that has the 3 dots.
then in the getView() or newView() method you set the listener to the 3 dots image.
i think that PopupMenu is what you are looking for, it's is supported since API 11.
if you want to support also earlier version of the API you can use PopupMenu class provided by the support library v7.
the usage is pretty straight forward.
you define it with the id of the view you want the menu to show next to, and then you can directly inflate a menu resource there as if it was a common menu.
Now showDialog is deprecated, use PopupMenu instead
And AppCompat PopupMenu f you want to support version before V11
public class MainActivity extends Activity {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_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
}
});//closing the setOnClickListener method
}
}
You have to set the Listener of the Button in the getView()-Method of your List-Adapter.
In this getView()-Method you assign a Layout to one List-Item. if you have done this, you just have to set the Listener on this View (Button), and handle the onClick() Event.
Not sure if i understand you correctly but you can trigger this method to open a pop up dialog with a listview.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Title if Any");
builder.setItems(R.array.listoptions, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int itemClicked) {
String[] option_array = getResources().getStringArray(R.array.listoptions);
String optionSelected = option_array[itemClicked];
}
});
return builder.create();
}
See Adding a List
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="listoption">
<item>Install</item>
<item>Add to listview</item>
</string-array>
</resources>
Hope this helps.
I am using ActionBarSherlock, in the ActionBar i have this custom layout to appear when i click on the searchIcon.
public boolean onCreateOptionsMenu(final Menu menu) {
LayoutInflater inflater = getLayoutInflater();
final View view = inflater.inflate(R.layout.on_search_icon_clicked,null, false);
view.findViewById(R.id.search_image).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText searchET = (EditText) view.findViewById(R.id.search_editText);
String s = searchET.getText().toString();
Toast.makeText(getBaseContext(), "Searching for: " + s,1000).show();
}
});
menu.add("Search")
.setIcon(R.drawable.ic_search)
.setActionView(view)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return true;
}
on_search_icon_clicked.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/search_image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:src="#drawable/ic_search"
android:clickable="true"
android:contentDescription="#string/seach_icon" />
<EditText
android:id="#+id/search_editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/search_image"
android:hint="#string/search"
android:singleLine="true" />
</RelativeLayout>
So, i click on the SearchIcon ---> i get the custom layout with editText and ImageView ---> click on editText, opens softkeyboard ---> enters string and clicks the imageView ---> shows me the toast.
Its fine till here.
The problem is:
i close the softkeyboard using device back button ---> then close the custom layout using ActionBar Home icon click ---> now click the searchIcon again, which reopens the custom layout, with editText filled with previously searched string ---> click on the editText, the softkeyboard doesn't open up (here is the problem).
Please help, i have no idea why its not working as expected.
Thank You
I have faced this problem before and here is my solution
//your_menu
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_search"
android:orderInCategory="0"
android:icon="#drawable/btn_search"
android:title="Search"
android:actionLayout="#layout/on_search_icon_clicked"
android:showAsAction="always|collapseActionView"
/>
</menu>
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getSupportMenuInflater().inflate(R.menu.your_menu, menu);
mSearchbar = (MenuItem) menu.findItem(R.id.menu_search);
View actionview = mSearchbar.getActionView();
mEtSearchbar = ((EditText) actionview.findViewById(R.id.search_editText));
mEtSearchbar.setOnEditorActionListener(this);
mEtSearchbar.addTextChangedListener(this);
super.onCreateOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Intent intent;
switch (item.getItemId())
{
case R.id.menu_search:
mEtSearchbar.clearFocus();
(new Handler()).postDelayed(new Runnable() {
public void run() {
mEtSearchbar.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0, 0, 0));
mEtSearchbar.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
}
}, 100);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
mEtSearchbar ~ your searchET