-2
我對android比較陌生,而且我被困在這個問題上。我創建了一個啓動對話框的按鈕。 AlertDialog(具體)然後以編程方式創建一個listView併爲其分配一個適配器。現在用戶可以點擊一些元素,並且ListView中的textView元素變爲紅色。然後我存儲被點擊的元素。現在,當我再次創建對話框時,被點擊的相同文本變成白色。如何在AlertDialog中獲取ListView的元素
所以我的問題是,如何事先訪問listView的元素,所以我可以改變以前點擊的項目的顏色。
這是Java代碼:
private void populateListView(String[] els) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.single_listview_item,R.id.txtitem, els);
list = new ListView(this);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ViewGroup vg=(ViewGroup)view;
TextView txt=(TextView)vg.findViewById(R.id.txtitem);
if(!currentList.isSelected(position)) {
txt.setBackgroundResource(R.color.redPastel);
currentList.select(position);
}
else{
txt.setBackgroundResource(R.color.white);
currentList.unselect(position);
}
}
});
}
//the listener for the button
public void showDialogListView(View view){
String [] selection = {};
Button buttonUsed = null;
switch (view.getId()){
case R.id.cuisineButton:
selection = cuisines.getArray();
currentList = cuisines;
buttonUsed = (Button) findViewById(R.id.cuisineButton);
break;
case R.id.mealTimeButton:
selection = times.getArray();
currentList = times;
buttonUsed = (Button) findViewById(R.id.mealTimeButton);
break;
}
populateListView(selection);
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
final Button finalButtonUsed = buttonUsed;
builder.setPositiveButton("Select",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finalButtonUsed.setText(currentList.getSelectionText());
}
});
builder.setNegativeButton("Cancel",null);
builder.setView(list);
AlertDialog dialog=builder.create();
dialog.show();
}
}
這是單一元素XML的佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txtitem"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:textSize="25sp"
android:gravity="center"
/>
</LinearLayout>
保存位置並通過list.getItemAtPosition() – jfxu
訪問它請參閱http://stackoverflow.com/questions/3888015/androidto-set-an-item-as-selected-wh en-the-listview-打開 – diedu
非常感謝! –