如何在Android对话框中自定义CheckMark颜色。默认情况下,CheckMark的颜色为绿色。我想将其自定义为不同的颜色。
<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>
您可以在Android Google文档上找到详细的完整文档。
要更改多选对话框中的复选框,您需要为对话框编写自定义适配器,以便能够访问列表视图。
然后,您可以调用CheckedTextView类的setCheckMarkDrawable
方法。
以下是一个示例:
在res/drawable
目录下有一个名为default_checkbox.xml
的文件。<?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/
checkbox_dialog.setTitle("主标题在这里");
checkbox_dialog.setMultiChoiceItems(myitems, choiceitems, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { Log.d("TAG","正在选择项目");} });
- Karthik