我声明这个适配器:
ArrayAdapter<Problem> adapter;
我也在此声明ArrayList:
ArrayList<Problem> problems = new ArrayList <Problem>( );
我的Problem类只有两个字段:problemId和problemName。
我调用远程数据库并填充数据,如下所示:
for ( int i = 0; i < obj.length(); i++ )
{
JSONObject o = obj.getJSONObject(i);
problem_title = o.getString("problem_title");
problem_id = o.getString("problem_id");
Problem p = new Problem ( );
p.setProblemId(problem_id);
p.setProblemId(problem_title);
problems.add( p );
}
adapter.notifyDataSetChanged();
因此,显示在屏幕上的内容是对象引用,但我想要显示的是名称,当用户单击该项目时,我也应该能够在侦听器中检索该项目的id:
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), (( TextView ) view).getText(),
Toast.LENGTH_SHORT).show();
// For now just do something simple like display a responsive message
Log.d( "MyProblemsActivity" , "A choice was made from the list: " + (( TextView ) view).getText() );
Log.d( "MyProblemsActivity" , "position: " + position );
Log.d( "MyProblemsActivity" , "id: " + id );
}
});
非常感谢您的帮助!!!!
谢谢!
我不确定我是否清楚这个问题,但这可能会有所帮助。。。
通过使用标签,您可以在Android中使用任何GUI元素(View)存储一段数据。
以下是View::setTag函数:http://developer.android.com/reference/android/view/View.html#setTag(java.lang.Object)
"…标记也可以用于在视图中存储数据,而无需使用其他数据结构。"
我认为只需要重写Problem对象的th-toString()方法。类似的东西
public String toString() {
return problemName;
}
这是ArrayAdapter将用于填充TextView的默认文本。