【发布时间】:2012-01-19 07:16:59
【问题描述】:
我有 9 个 ImageView,当 onClick 每次打开一个颜色选择器时,我希望颜色选择器更改与当时使用 onclick 的同一视图相关的可绘制对象的颜色。我不确定如何执行此操作?我在网上搜索了示例,但似乎找不到任何相关的内容。
【问题讨论】:
标签: android colors background drawable color-picker
我有 9 个 ImageView,当 onClick 每次打开一个颜色选择器时,我希望颜色选择器更改与当时使用 onclick 的同一视图相关的可绘制对象的颜色。我不确定如何执行此操作?我在网上搜索了示例,但似乎找不到任何相关的内容。
【问题讨论】:
标签: android colors background drawable color-picker
如果您想从中选择一组固定的颜色,您可以使用level list drawable。在 XML 中,它可能看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:drawable="@drawable/color_0"
android:maxLevel="0" />
<item
android:drawable="@drawable/color_1"
android:maxLevel="1" />
. . .
</level-list>
然后,您可以将其设为 ImageView 的可绘制对象,并通过调用图像视图的 setImageLevel() 方法来选择要显示的颜色。
编辑
您要求提供以编程方式执行此操作的示例。假设您有以下布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="0"
android:onClick="changeColor"
android:text="Change color" />
<View
android:layout_width="50dp"
android:layout_height="50dp"
android:tag="color_0" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="1"
android:onClick="changeColor"
android:text="Change color" />
<View
android:layout_width="50dp"
android:layout_height="50dp"
android:tag="color_1" />
</LinearLayout>
<!-- etc. -->
</LinearLayout>
然后,在您的活动中,定义您的处理函数,如下所示:
public void changeColor(View view) {
String tag = "color_" + view.getTag();
View target = findViewById(android.R.id.content).findViewWithTag(tag);
int color = getColorFromUser();
target.setBackgroundColor(color); // or whatever you want to do
}
人们可能希望在此过程中包括一些检查空标签、未找到的视图、用户取消颜色选择等。
【讨论】: