我正在制作一个安卓程序。在我的应用程序中,我使用了一个单选选择 AlertDialog,其项目是以编程方式添加的。我想做的是:
- 下次用户打开对话框时为所选项目设置背景颜色,
- 在对话框中间显示所选项目(这是一个问题,因为大约有 20 个项目)。
这是我所拥有的:XML:
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp" >
<Button
android:id="@+id/selectDateButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Please, select date" />
</LinearLayout>
爪哇:
public class ExperimentListView extends Activity {
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static Calendar calendar = Calendar.getInstance();
private static Button selectDateButton;
private static String[] items;
private static int selectedDatePosition = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_ex);
selectDateButton = (Button)findViewById(R.id.selectDateButton);
selectDateButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
items = new String[20];
for (int i = 0; i < 20; i++) {
items[i] = DATE_FORMAT.format(calendar.getTime());
calendar.add(Calendar.DATE, 1);
}
showListView();
}
});
}
private void showListView() {
AlertDialog.Builder builder = new AlertDialog.Builder(ExperimentListView.this);
builder.setTitle("Select date");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selectedDatePosition = which;
selectDateButton.setText(items[selectedDatePosition]);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.getListView().setSelection(selectedDatePosition);
alertDialog.show();
}
}
到目前为止,我还没有找到解决方案,如果有人可以提供帮助,我将不胜感激。提前致谢。