【发布时间】:2010-08-16 07:07:00
【问题描述】:
如何在对话框中自定义 android 中 CheckMark 颜色的颜色。目前,默认情况下,复选标记的颜色默认为绿色。我想将其定制为不同的颜色选择
【问题讨论】:
标签: android
如何在对话框中自定义 android 中 CheckMark 颜色的颜色。目前,默认情况下,复选标记的颜色默认为绿色。我想将其定制为不同的颜色选择
【问题讨论】:
标签: android
如果您查看styles.xml from android system,您会看到复选框样式定义如下:
<style name="Widget.CompoundButton.CheckBox">
<item name="android:background">@android:drawable/btn_check_label_background</item>
<item name="android:button">@android:drawable/btn_check</item>
</style>
如果你搜索系统的资源,你会看到 btn_check 是一个可绘制的选择器,有 2 个状态(开/关),检查是否为绿色。
因此,如果您想拥有自己的可绘制颜色,您应该这样做:
- 创建一个styles.xml
- 定义要使用的 2 个可绘制对象
- 创建支持选择器的 xml 文件
你可以在the android google doc.找到完整的文档
【讨论】:
要更改多选对话框中的复选框,您需要为对话框自定义适配器,以便访问列表的视图。
然后,调用 CheckedTextView 类的方法setCheckMarkDrawable。
这是一个例子:
文件default_checkbox.xml在res/drawable内
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:drawable="@drawable/checkbox_checked" /> <!-- checked -->
<item android:state_pressed="true"
android:drawable="@drawable/checkbox_checked" /> <!-- pressed -->
<item android:drawable="@drawable/checkbox_default" /> <!-- default -->
</selector>
文件DialogUtil.java
package example.dialog;
import android.app.AlertDialog;
import android.content.Context;
import android.util.Log;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
public class DialogUtil {
private DialogUtil() {
}
public static AlertDialog show(Context context) {
String[] items = {"text 1", "text 2", "text 3"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Test")
.setPositiveButton("OK", null)
.setAdapter(new CustomAdapter(context, items), null);
AlertDialog dialog = builder.show();
ListView list = dialog.getListView();
list.setItemsCanFocus(false);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list.setOnItemClickListener(listener);
return dialog;
}
private static OnItemClickListener listener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("DialogUtil", "Clicked on " + view);
}
};
private static class CustomAdapter extends ArrayAdapter<String> {
public CustomAdapter(Context context, String[] array) {
super(context, android.R.layout.simple_list_item_multiple_choice, array);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (view instanceof CheckedTextView) {
CheckedTextView checkedView = (CheckedTextView) view;
checkedView.setCheckMarkDrawable(R.drawable.default_checkbox);
}
return view;
}
}
}
注意:如果您只是使用AlertDialog,那么在获取ListView 之前,您首先调用show,如上所述。
但是,如果您使用DialogFragment 和onCreateDialog,那么您会在onStart 中获得ListView。
【讨论】:
您必须使用修改后的可绘制资源覆盖复选框小部件样式。 这是从样式/主题开始的好指南http://brainflush.wordpress.com/2009/03/15/understanding-android-themes-and-styles/
【讨论】: