【问题标题】:Apply image to a menu item dynamically将图像动态应用到菜单项
【发布时间】:2019-01-14 05:03:46
【问题描述】:

我正在尝试使用 glide 以编程方式将图像添加到菜单项。

ma​​in_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">
<item
    android:id="@+id/action_profile_pic"
    android:icon="@mipmap/profile_pic"
    android:orderInCategory="100"
    android:title=""
    app:showAsAction="always" />

Java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_menu, menu);

    RequestOptions requestOptions = new RequestOptions();
    requestOptions.placeholder(R.mipmap.profile_pic);
    requestOptions.error(R.mipmap.profile_pic);

    MenuItem itemProfilePic = menu.getItem(0);
    //View view = findViewById(R.id.action_profile_pic);

    if (savedProfilePic != null) {
        Glide.with(this)
                .setDefaultRequestOptions(requestOptions)
                .load(Uri.parse(savedProfilePic))
                .into(itemProfilePic);
    }
    return true;

但是,我不能使用这种方法,因为资源是 MenuItem 而不是 ImageView。将其投射到 ImageView 也不起作用。

如果图像不在drawables文件夹中,我怎样才能达到预期的效果,它是由用户设置的,因此下面的方法也不能使用:

itemProfilePic.setActionView(savedProfilePic); 接受一个整数值

最终结果

【问题讨论】:

标签: java android xml android-image


【解决方案1】:

MenuItem 接口有一个方法:setIcon(Drawable d)

  1. 获取对您要更新的MenuItem 的引用。
  2. 将要设置的图像转换为BitmapDrawable
  3. 根据需要调整drawable并通过MenuItem.setIcon()方法设置。

您似乎也可以从您正在使用的图像加载器库中实现custom target。自定义目标可以包装 MenuItem

注意: 由于您正在扩充 XML 菜单,因此它很可能会被刷新。因此,在扩展 XML 之后也执行图像图标更新。

【讨论】:

    【解决方案2】:

    制作自定义工具栏,然后您可以使用图像视图动态更改图像

    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        app:contentInsetStart="0dp"
        android:background="@color/primaryColor"
        android:layout_height="wrap_content" >
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <ImageView
                android:src="@drawable/ic_perm_24dp"
                android:layout_alignParentEnd="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
    
        </RelativeLayout>
    
    
    </android.support.v7.widget.Toolbar>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      相关资源
      最近更新 更多