setView()
警报对话框的方法很有用,您可以将ListView
对话框设置为自定义视图。
例如。
CustomDialogListAdapter adapter = new CustomDialogListAdapter();
ListView list = new ListView(this);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
setTitle("item : " + arg2);
}
});
final Builder dialogBuilder = new Builder(this);
dialogBuilder.setTitle("Custom List Dialog");
dialogBuilder.setView(list);
dialogBuilder.create().show();
您可以为列表创建自定义适配器,如下所示
class CustomDialogListAdapter extends BaseAdapter {
private String[] data = { "People Names", "Dog Names", "Cat Names", "Fish Names" };
private ArrayList<Boolean> checkboxStatus = new ArrayList<Boolean>();
public CustomDialogListAdapter() {
int count = data.length;
for (int i = 0; i < count; i++)
checkboxStatus.add(false);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.raw_dialog_item, null);
holder = new ViewHolder();
holder.chk = (CheckBox) convertView.findViewById(R.id.chkbox);
holder.chk.setOnCheckedChangeListener(checkboxListener);
holder.txt = (TextView) convertView.findViewById(R.id.txtTitle);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.chk.setTag("" + position);
holder.chk.setChecked(checkboxStatus.get(position));
holder.txt.setText(data[position]);
return convertView;
}
class ViewHolder {
CheckBox chk;
TextView txt;
}
private OnCheckedChangeListener checkboxListener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int position = Integer.parseInt(buttonView.getTag().toString());
checkboxStatus.set(position, isChecked);
}
};
@Override
public int getCount() {
return data.length;
}
@Override
public Object getItem(int position) {
return data[position];
}
@Override
public long getItemId(int position) {
return position;
}
}
列表项的原始文件 (raw_dialog_item.xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" >
<CheckBox
android:id="@+id/chkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/chkbox"
android:text="@string/hello_world" />
</RelativeLayout>