12

我想创建一个类似于 Google+ 应用通知的通知图标视图。不同之处在于我需要能够在运行时更改颜色,因为 Google+ 图标为灰色或红色,所以我假设它们使用的是 StateListDrawable。

最好的方法是什么?我更喜欢有圆角的剪裁角,并可以选择在里面有一个可绘制的。此自定义视图也将放置在操作栏中。我仍然需要视图来响应 android:background state list drawables,这样我就可以点击并选择相应的工作。

此自定义视图也将放置在操作栏中。

右上角有通知图标的 Google+ 应用程序显示为灰色,中间有一个 0。

4

1 回答 1

24

我通过执行以下操作解决了这个问题。

创建这个以使圆角形状具有纯色。这还添加了半透明的黑色,使其在黑色背景下看起来更加立体。 res/drawable/shape_notification.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
    <stroke android:color="#33000000" android:width="2dp"/>
    <corners android:radius="4dp" />
    <solid android:color="#99333333"/>
</shape>

图层可绘制对象将用作操作栏项目上的实际可绘制对象。它的背景(上面写着)覆盖有扳手图标。 res/drawable/layer_customizer.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/shape_notification" />
    <item android:drawable="@drawable/ic_menu_preferences" />
</layer-list>

更改颜色的 Java 代码。目标视图是分配了 layer_customizer 可绘制对象的对象。传入的颜色会改变 shape_notification.xml 的实心标签颜色。

public static void setCustomizerDrawableColor(final View target, final int color) {
  final Drawable d = target.getDrawable();
  LayerDrawable layer = (LayerDrawable)d;
  GradientDrawable gradient = (GradientDrawable)layer.getDrawable(0);
  gradient.setColor(color);
  gradient.invalidateSelf();
  layer.invalidateSelf();
  target.invalidate();
}

使用这些图层创建布局。 res/layout/actionview_customizer.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/ActionViewCustomizer"
    android:src="@drawable/layer_customizer"
    android:contentDescription="@string/customize"
    style="@style/ActionBarButton" />

要将自定义布局放入 ActionBar,请将此菜单项添加到其中: res/menu/actionbar_main.xml

<item android:id="@+id/MenuItemCustomize"
  android:icon="@drawable/layer_customizer"
  android:title="@string/customize"
  android:showAsAction="always"
  android:actionLayout="@layout/actionview_customizer"
   />

然后在加载操作栏后使用此代码获取按钮的句柄。这发生在您的活动中。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.actionbar_main, menu);
    final ActionBar actionBar = getActionBar();
    final MenuItem customizerItem = menu.findItem(R.id.MenuItemCustomize);
    View v = customizerItem.getActionView();
    customizerActionView = (ImageButton) v;
    customizerActionView.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            onOptionsItemSelected(customizerItem);
        }
    });
}

如果您想查看完整的源代码,请查看我在其中使用的应用程序源代码。http://code.google.com/p/motivatormaker-android/source/browse/MakeMotivator/src/com/futonredemption/makemotivator /activities/MainActivity.java

于 2012-02-12T23:06:06.223 回答