大家好我想在一个列表中水平显示多个项目。从具有两个按钮确定和取消的对话框中选择此项目。单击“确定”时,它应从编辑文本中选择值,并从对话框中选择字符串值,并在列表中水平显示。
Array List Adapter
public class VehicleListAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> vehicle_no;
public VehicleListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
this.context = context;
this.vehicle_no = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the vehicle number we are displaying
String my_vehicle = vehicle_no.get(position);
//get the inflater and inflate the XML layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.vehicle_num_layout, null);
TextView txt_vehicle_num = (TextView) view.findViewById(R.id.txt_vehicle_num);
txt_vehicle_num.setText(my_vehicle);
return view;
}
}
Activity with the list
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
if(userInput.getText().toString().trim().length()==0) {
userInput.setError("Vehicle Number Required");
focus.start();
String stime = focus.getText().toString();
}
else {
result.setText(userInput.getText());
ListView list = (ListView) findViewById(R.id.list);
vehicle_list.add(userInput.getText().toString().trim());
VehicleListAdapter listAdapter = new VehicleListAdapter(StartWatch.this, 0, vehicle_list);
list.setAdapter(listAdapter);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
答案 0 :(得分:0)
首先,每当用户点击确定对话框时,为什么要创建新的列表视图。从对话框正面按钮单击中删除此行ListView list = (ListView) findViewById(R.id.list);
。
在正面按钮中单击
后,按如下所示添加行VehicleListAdapter listAdapter = new VehicleListAdapter(StartWatch.this, 0, vehicle_list);
list.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged(); // Add this line to tell adapter that data has been changed