我如何在弹出菜单中调用自己的方法

时间:2014-07-25 07:08:27

标签: java android

我想在popupmenu中显示listview?   我为listview构建了initializeVars()方法   如何在我的showPopupMenu(View v)上使用此方法   告诉我这个程序的解决方案

public void initializeVars(){
    lv_sample = (ListView)findViewById(R.id.lv_sample);
    adapter = new ArrayAdapter<String>(this, R.layout.setlanguage, R.id.tv_content, values);
    if(adapter==null) 
        return;
    lv_sample.setAdapter(adapter);
}

private void showPopupMenu(View v){
    PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
    popupMenu.getMenuInflater().inflate(R.menu.main, popupMenu.getMenu());

    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

    public boolean onMenuItemClick(MenuItem item) {
        Toast.makeText(MainActivity.this, item.toString(), Toast.LENGTH_LONG).show();
        return true;
    }
});
popupMenu.show();

1 个答案:

答案 0 :(得分:0)

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:id="@+id/pop1"
    android:orderInCategory="100"
    android:showAsAction="never"
    android:title="@string/hello_world"/>
<item
    android:id="@+id/pop2"
    android:orderInCategory="100"
    android:showAsAction="never"
    android:title="@string/hello_world"/>
<item 
    android:id="@+id/pop3"
    android:orderInCategory="100"
    android:showAsAction="never"
    android:title="@string/hello_world"/>

使用PopupMenu对其进行充气将默认将项目显示为列表....

但是,如果您仍想显示列表,那么:

你可以扩展DialogFragment ......

public class DefaultViewDialog extends DialogFragment{

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // TODO Auto-generated method stub

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
    //following commented code produces check box list in the dialog
    //dialogBuilder.setMultiChoiceItems(R.array.DefaultView_array, null, null);

    /* setItems(id) creates a simple list */
    dialogBuider.setItems(R.array.DefaultView_array, null, null);
    return dialogBuilder.create();

}

}

希望我能帮助:)