在android中添加上下文菜单图标

发布于 2024-07-30 00:17:45 字数 362 浏览 7 评论 0原文

我有一个带有 ContextMenu 的 Listview,但是当我为 ContextMenu setIcon 时,它看起来不起作用

public void onCreateContextMenu(ContextMenu menu , View v, 
        ContextMenuInfo menuInfo){

    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(0, DELETE_ID, 0, R.string.context_menu_favorite)
        .setIcon(android.R.drawable.btn_star);      
}

I have a Listview with a ContextMenu, but when I setIcon for ContextMenu look like it doesn't work

public void onCreateContextMenu(ContextMenu menu , View v, 
        ContextMenuInfo menuInfo){

    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(0, DELETE_ID, 0, R.string.context_menu_favorite)
        .setIcon(android.R.drawable.btn_star);      
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

云之铃。 2024-08-06 00:17:49

这可能是您所缺少的:

popup.setForceShowIcon(true)

This might be what you are missing:

popup.setForceShowIcon(true)
不念旧人 2024-08-06 00:17:49

虽然 API 不支持上下文菜单中的图标,但我们总是可以通过使用看起来像上下文菜单的我们自己的视图来膨胀对话框来伪造它。

复制粘贴以下文件即可完成这项工作:

MainActivity.java

public class MainActivity extends Activity {

List<ContextMenuItem> contextMenuItems;
Dialog customDialog;

LayoutInflater inflater;
View child;
ListView listView;
ContextMenuAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    inflater = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    child = inflater.inflate(R.layout.listview_context_menu, null);
    listView = (ListView) child.findViewById(R.id.listView_context_menu);

    contextMenuItems = new ArrayList<ContextMenuItem>();
    contextMenuItems.add(new ContextMenuItem(getResources().getDrawable(
            R.drawable.ic_launcher), "Facebook"));
    contextMenuItems.add(new ContextMenuItem(getResources().getDrawable(
            R.drawable.ic_launcher), "Scanner"));

    adapter = new ContextMenuAdapter(this,
            contextMenuItems);
    listView.setAdapter(adapter);

            listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            customDialog.dismiss();
            if (position == 0)
                Toast.makeText(MainActivity.this, "00", Toast.LENGTH_SHORT)
                        .show();

            if (position == 1)
                Toast.makeText(MainActivity.this, "11", Toast.LENGTH_SHORT)
                        .show();

        }
    });

    customDialog = new Dialog(this);
    customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    customDialog.setContentView(child);
    customDialog.show();
    }

}

ContextMenuItem.java

public class ContextMenuItem {

Drawable drawable;
String text;

public ContextMenuItem(Drawable drawable, String text) {
    super();
    this.drawable = drawable;
    this.text = text;
}

public Drawable getDrawable() {
    return drawable;
}

public void setDrawable(Drawable drawable) {
    this.drawable = drawable;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

}

ContextMenuAdapter.java

public class ContextMenuAdapter extends BaseAdapter {
Context context;
List<ContextMenuItem> listContextMenuItems;
LayoutInflater inflater;

public ContextMenuAdapter(Context context,
        List<ContextMenuItem> listContextMenuItems) {
    super();
    this.context = context;
    this.listContextMenuItems = listContextMenuItems;
}

static class ViewHolder {
    protected ImageView imageView;
    protected TextView textView;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewHolder = new ViewHolder();
        convertView = inflater.inflate(R.layout.context_menu_item, parent,
                false);
        viewHolder.imageView = (ImageView) convertView
                .findViewById(R.id.imageView_menu);
        viewHolder.textView = (TextView) convertView
                .findViewById(R.id.textView_menu);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.imageView.setImageDrawable(listContextMenuItems
            .get(position).getDrawable());
    viewHolder.textView.setText(listContextMenuItems.get(position)
            .getText());
    return convertView;

}

@Override
public int getCount() {
    return listContextMenuItems.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

}

context_menu_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp" >

<ImageView
    android:id="@+id/imageView_menu"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:scaleType="fitXY" />

<TextView
    android:id="@+id/textView_menu"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginLeft="10dp"
    android:layout_toRightOf="@+id/imageView_menu" />

</RelativeLayout>

listview_context_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listView_context_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/view" />

While the API doesn't support icons in Context Menu, but we can always fake it by inflating a Dialog with our own view that looks like context menu.

Copy-pasting the following files exactly will do the job:

MainActivity.java

public class MainActivity extends Activity {

List<ContextMenuItem> contextMenuItems;
Dialog customDialog;

LayoutInflater inflater;
View child;
ListView listView;
ContextMenuAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    inflater = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    child = inflater.inflate(R.layout.listview_context_menu, null);
    listView = (ListView) child.findViewById(R.id.listView_context_menu);

    contextMenuItems = new ArrayList<ContextMenuItem>();
    contextMenuItems.add(new ContextMenuItem(getResources().getDrawable(
            R.drawable.ic_launcher), "Facebook"));
    contextMenuItems.add(new ContextMenuItem(getResources().getDrawable(
            R.drawable.ic_launcher), "Scanner"));

    adapter = new ContextMenuAdapter(this,
            contextMenuItems);
    listView.setAdapter(adapter);

            listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            customDialog.dismiss();
            if (position == 0)
                Toast.makeText(MainActivity.this, "00", Toast.LENGTH_SHORT)
                        .show();

            if (position == 1)
                Toast.makeText(MainActivity.this, "11", Toast.LENGTH_SHORT)
                        .show();

        }
    });

    customDialog = new Dialog(this);
    customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    customDialog.setContentView(child);
    customDialog.show();
    }

}

ContextMenuItem.java

public class ContextMenuItem {

Drawable drawable;
String text;

public ContextMenuItem(Drawable drawable, String text) {
    super();
    this.drawable = drawable;
    this.text = text;
}

public Drawable getDrawable() {
    return drawable;
}

public void setDrawable(Drawable drawable) {
    this.drawable = drawable;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

}

ContextMenuAdapter.java

public class ContextMenuAdapter extends BaseAdapter {
Context context;
List<ContextMenuItem> listContextMenuItems;
LayoutInflater inflater;

public ContextMenuAdapter(Context context,
        List<ContextMenuItem> listContextMenuItems) {
    super();
    this.context = context;
    this.listContextMenuItems = listContextMenuItems;
}

static class ViewHolder {
    protected ImageView imageView;
    protected TextView textView;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewHolder = new ViewHolder();
        convertView = inflater.inflate(R.layout.context_menu_item, parent,
                false);
        viewHolder.imageView = (ImageView) convertView
                .findViewById(R.id.imageView_menu);
        viewHolder.textView = (TextView) convertView
                .findViewById(R.id.textView_menu);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.imageView.setImageDrawable(listContextMenuItems
            .get(position).getDrawable());
    viewHolder.textView.setText(listContextMenuItems.get(position)
            .getText());
    return convertView;

}

@Override
public int getCount() {
    return listContextMenuItems.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

}

context_menu_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp" >

<ImageView
    android:id="@+id/imageView_menu"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:scaleType="fitXY" />

<TextView
    android:id="@+id/textView_menu"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginLeft="10dp"
    android:layout_toRightOf="@+id/imageView_menu" />

</RelativeLayout>

listview_context_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listView_context_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/view" />
时光无声 2024-08-06 00:17:48

虽然 Android API 不允许在上下文菜单中使用图标,但您可以看到 Android 在很多地方都在使用它们。 长按主屏幕就是一个很好的例子。

我花时间深入研究 Launcher 和 AnyCut 源代码,发现 Google 正在使用他们自己的自定义类,该类扩展了 BaseAdapter 以及他们自己的自定义布局。

我能够几乎完全复制他们的类和布局,并在我自己的应用程序中使用它来完成。 如果您要搜索该类,则该类名为 AddAdapter.java。

享受!

While the Android API does not allow for Icons in Context menus you can see many places where Android is using them. Long pressing your home screen is one good example.

I took the time to dig through the Launcher and AnyCut source and found that Google is using their own custom class that extends a BaseAdapter along with their own custom layout.

I was able to copy their class and layout almost exactly and use it in my own app to accomplish. The class if you want to search for it is called AddAdapter.java.

Enjoy!

送舟行 2024-08-06 00:17:47

我是通过这种方式做到的:

参考截图:

在此处输入图像描述

菜单:

menu_病人_语言.xml

<?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:tools="http://schemas.android.com/tools"
    tools:context=".activities.PatientSelectionActivity">

    <item
        android:id="@+id/menuEnglish"
        android:icon="@drawable/language_english"
        android:title="@string/english" />

    <item
        android:id="@+id/menuFrench"
        android:icon="@drawable/language_french"
        android:title="@string/french" />

</menu>

样式:

style.xml:

  <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->

        <item name="android:popupMenuStyle">@style/popupMenuStyle</item>

    </style>

  <!--- Language selection popup -->

    <style name="popupMenuStyle" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:textColor">@color/colorPrimary</item>
        <item name="android:itemBackground">@android:color/white</item>
    </style>

Java代码:

 private void showPopup(View v) {

        Context wrapper = new ContextThemeWrapper(this, R.style.popupMenuStyle);
        PopupMenu mypopupmenu = new PopupMenu(wrapper, v);

        setForceShowIcon(mypopupmenu);
        MenuInflater inflater = mypopupmenu.getMenuInflater();
        inflater.inflate(R.menu.menu_patient_language, mypopupmenu.getMenu());
        mypopupmenu.show();
//        mypopupmenu.getMenu().getItem(0).setIcon(getResources().getDrawable(R.mipmap.ic_launcher));
        mypopupmenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                txtPreferredLanguage.setText(item.getTitle().toString());
                switch (item.getItemId()) {
                    case R.id.menuEnglish:
                        // Your code goes here
                        break;

                    case R.id.menuFrench:
                        // Your code goes here
                        break;
                }
                return false;
            }
        });
    }

    private void setForceShowIcon(PopupMenu popupMenu) {
        try {
            Field[] mFields = popupMenu.getClass().getDeclaredFields();
            for (Field field : mFields) {
                if ("mPopup".equals(field.getName())) {
                    field.setAccessible(true);
                    Object menuPopupHelper = field.get(popupMenu);
                    Class<?> popupHelper = Class.forName(menuPopupHelper.getClass().getName());
                    Method mMethods = popupHelper.getMethod("setForceShowIcon", boolean.class);
                    mMethods.invoke(menuPopupHelper, true);
                    break;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

希望这对您有所帮助。

完成

I did it by this way:

Reference screenshot:

enter image description here

Menu:

menu_patient_language.xml

<?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:tools="http://schemas.android.com/tools"
    tools:context=".activities.PatientSelectionActivity">

    <item
        android:id="@+id/menuEnglish"
        android:icon="@drawable/language_english"
        android:title="@string/english" />

    <item
        android:id="@+id/menuFrench"
        android:icon="@drawable/language_french"
        android:title="@string/french" />

</menu>

Style:

style.xml:

  <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->

        <item name="android:popupMenuStyle">@style/popupMenuStyle</item>

    </style>

  <!--- Language selection popup -->

    <style name="popupMenuStyle" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:textColor">@color/colorPrimary</item>
        <item name="android:itemBackground">@android:color/white</item>
    </style>

Java code:

 private void showPopup(View v) {

        Context wrapper = new ContextThemeWrapper(this, R.style.popupMenuStyle);
        PopupMenu mypopupmenu = new PopupMenu(wrapper, v);

        setForceShowIcon(mypopupmenu);
        MenuInflater inflater = mypopupmenu.getMenuInflater();
        inflater.inflate(R.menu.menu_patient_language, mypopupmenu.getMenu());
        mypopupmenu.show();
//        mypopupmenu.getMenu().getItem(0).setIcon(getResources().getDrawable(R.mipmap.ic_launcher));
        mypopupmenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                txtPreferredLanguage.setText(item.getTitle().toString());
                switch (item.getItemId()) {
                    case R.id.menuEnglish:
                        // Your code goes here
                        break;

                    case R.id.menuFrench:
                        // Your code goes here
                        break;
                }
                return false;
            }
        });
    }

    private void setForceShowIcon(PopupMenu popupMenu) {
        try {
            Field[] mFields = popupMenu.getClass().getDeclaredFields();
            for (Field field : mFields) {
                if ("mPopup".equals(field.getName())) {
                    field.setAccessible(true);
                    Object menuPopupHelper = field.get(popupMenu);
                    Class<?> popupHelper = Class.forName(menuPopupHelper.getClass().getName());
                    Method mMethods = popupHelper.getMethod("setForceShowIcon", boolean.class);
                    mMethods.invoke(menuPopupHelper, true);
                    break;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

Hope this would help you sure.

Done

鸠书 2024-08-06 00:17:47

该库允许您使用标准 XML 菜单创建带有图标的上下文菜单(实现为 AlertDialog)。

https://code.google.com/p/android-icon-context-菜单/

This library allows you to have a context menu (implemented as AlertDialog) with icons using a standard XML menu.

https://code.google.com/p/android-icon-context-menu/

咽泪装欢 2024-08-06 00:17:46

上下文菜单不支持图标。

注意:上下文菜单项不
支持图标或快捷键。

Context menus do not support icons.

Note: Context menu items do not
support icons or shortcut keys.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文