我从数据库(id,name)中获取数据,我想在 ListView 中显示(name)。当用户单击时,我需要获取数据库(id)来执行操作。我让它工作,但我的解决方案对于这么简单的事情来说似乎很复杂。我想以某种方式将(id)以隐藏的方式存储在 ListView 中,并在用户选择项目时能够检索它。这是我的解决方案:
class Route { //structure to store the data in ListView
public int id;
public String name;
public Route (int Id, String Name) {
id = Id;
name = Name;
}
}
// Create a custom adapter, we also created a corresponding
// layout (route_row) for each item of the ListView
public class MySimpleArrayAdapter extends ArrayAdapter<Route> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, ArrayList<Route> routes) {
super(context, R.layout.route_row, routes);
this.context = context;
//Get the list of string array to display in the ListView
String[] values = new String[routes.size()];
//Loop around all the items to get the list of values to be displayed
for (int i=0; i<routes.size(); i++) values[i] =
routes.get(i).id + " - " + routes.get(i).name;
//We added route.id to route.name for debugging but route.id is not necessary
this.values = values; //String array used to display data in the ListView
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.route_row, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.routeName);
textView.setText(values[position]);
return rowView;
}
}
//output is a JSON array composed of JSON object routes
void DisplayListView(String output) { (id, name)
ListView listView = (ListView) findViewById(R.id.listView1);
ArrayList<Route> list = new ArrayList<Route>();
//Convert the JSON to ArrayList<Route>
try {
JSONArray json = new JSONArray(output); //Get JSON array
JSONObject jsonObj;
int id;
String name;
for(int i=0;i<json.length();i++) {
jsonObj = json.getJSONObject(i); //Get each JSON object
id = jsonObj.getInt("Id");
name = jsonObj.getString("Name");
list.add( new Route(id, name));
}
}
catch (Exception ex) {
Log.w("Commute", ex.toString());
ex.printStackTrace();
}
//Create ArrayAdapter
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(getApplicationContext(),
list);
// Assign adapter to ListView
listView.setAdapter(adapter);
//Set a listener
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " +
((Route)parent.getItemAtPosition(position)).id,
Toast.LENGTH_LONG)
.show();
//It works when user clicks we display route.id
}
});
}
有没有更简单的方法来做到这一点?我发现了类似的问题,但没有简单或明确的答案。
我可以避免使用自定义适配器吗?我只想显示一个简单的 ListView,每行都有一个文本。
我可以避免循环 ArrayAdapter 为 adpater 创建 String 数组吗?这似乎确实是一种低效的方法。