【问题标题】:inflate popup menu items programmatically以编程方式膨胀弹出菜单项
【发布时间】:2011-08-17 14:40:49
【问题描述】:

我的活动中有一个按钮,按下它,将调用以下方法 -

private ArrayList<ListView> myListViewList;
private ArrayList<MyListAdapter> myAdapterList;

public void onPopupButtonClick(View button) {
    Log.v(TAG, "onPopupButtonClick");

    PopupMenu popup = new PopupMenu(this, button);
    Menu menu = popup.getMenu();

    // how do I display the myListViewList as items of in this popup menu
    // i.e how do I inflate myListViewList into menu object?
}

我知道如何以编程方式为活动执行此操作 - 创建线性布局和列表视图,最后在活动的上下文中使用 addContentView。

但是发现很难为上述弹出菜单场景做同样的事情。

【问题讨论】:

    标签: android


    【解决方案1】:

    检查弹出窗口的代码

     LayoutInflater inflater = (LayoutInflater) PopupMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     final View layout = inflater.inflate(R.layout.popup,        
     (ViewGroup)findViewById(R.id.popup_menu_root));
     PopupWindow pw = new PopupWindow(layout, 300,100, true);
     pw.dismiss();
     pw.showAtLocation(layout, Gravity.BOTTOM, 0, 10);
    

    您的新弹出式布局应如下所示:

    Popup.xml:

    <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/popup_menu_root"
       android:background="#FFFFFF"
       android:orientation="vertical"
       android:layout_width="wrap_content"
       android:layout_height="20dip" >
      <TextView android:id="@+id/popup_menu_button1"
         android:text="Copy"
         android:textColor="#000000"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content" />
     </LinearLayout>
    

    这条线决定了你的新视图(弹出窗口)的高度和宽度

      PopupWindow pw = new PopupWindow(layout, 300,100, true);
    

    pw.showAtLocation(layout, Gravity.BOTTOM, 0, 10);

    告诉弹出窗口应该显示在哪里..

    【讨论】:

    • 您好,您给我的代码 sn-p 告诉我如何创建 PopupWindow 实例。但我的问题是,如何将 listView 膨胀到生成的 PopupWindow 视图中?或者甚至有可能吗?我应该看对话框来实现我的目标吗?我的目标是在单击弹出菜单按钮时显示一个 listView(或 ListViews 的 ArrayList)。谢谢。
    • 是的。这甚至可能吗?另外,我想以编程方式膨胀 ListView,因为我可能必须在弹出视图中显示多个 ListView 内容(将在运行时确定)。
    • 经过一些实验,我发现可以在 popupWindow 视图中添加一个 listView(甚至是一个 listview 数组)。唯一的问题是没有一个元素是可聚焦的。但有趣的是,它们是可点击的。我必须找出为什么列表中的各个项目无法聚焦,即使我将其设置为明确地在列表的自定义适配器中。
    • get error 方法 findViewById(int) 未定义为 new View.OnClickListener(){} 类型。我在非活动类中夸大了这个
    猜你喜欢
    • 2020-04-04
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多