-2
私は比較的新しいアンドロイドです。この問題に取り組んでいます。 Dialogを起動するボタンを作成しました。 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-opens – diedu
ありがとうございました! –