我有一个活动来填充列表视图。我在活动的onCreate方法中创建了listview。现在我想为列表实现onclick listner。怎么做到这一点?
这是我的listview活动类:
public class PollStationActivity extends Activity {
static String response_str=null;
static String response_code=null;
String ac_code;
String ac_id;
String ac_lat;
String ac_lon;
String ac_name;
// Hashmap for ListView
ArrayList<HashMap<String, String>> PSList = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// no more this
setContentView(R.layout.activity_poll_station);
//sendPostRequest();
//Log.i("I am here","1");
final String status_code_from_prev= getIntent().getExtras().getString("status");
//Log.i("ss",status_code_from_prev);
ArrayList<PSItem> PSList = new ArrayList<PSItem>();
DatabaseHelper db = new DatabaseHelper(PollStationActivity.this);
ContentValues values = new ContentValues();
try {
db.createDataBase();
PSList = db.select(status_code_from_prev);
//Log.i("Count : ", " " + PSList.isEmpty());
} catch (IOException e) {
e.printStackTrace();
}
db.close();
String[] fromColumns = {"name"};
int[] toViews = {R.id.list_label_name}; // The TextView in simple_list_item_1
ListView listView1 = (ListView) findViewById(R.id.poll_list_listView);
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
Iterator<PSItem> i = PSList.iterator();
while(i.hasNext())
{
HashMap<String, String> map = new HashMap<String, String>();
PSItem objPSItem = i.next();
map.put("name", objPSItem.PS_NAME);
map.put("ps_Id", objPSItem.PS_ID);
fillMaps.add(map);
}
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.list_layout, fromColumns, toViews);
listView1.setAdapter(adapter);
}
}
我应该在哪里列出listview onclick listner?
答案 0 :(得分:1)
如果您使用的是ListView,则应使用OnItemClickListener。我会在你分配适配器后添加监听器。
我更喜欢使用以下解决方案来处理点击事件。
public class StartActivity extends Activity implements OnItemClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_start);
// Create adapter for the list view
ListView lw = (ListView) findViewById(R.id.WordsListView);
lw.setAdapter(adapter);
lw.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
答案 1 :(得分:1)
您可以在初始化后立即设置监听器,例如:
ListView listView1 = (ListView) findViewById(R.id.poll_list_listView);
listView1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//Handle the click
}
});
即使您尚未为列表设置适配器,也就是说没有显示任何项目,只要您已通过findViewById
初始化列表视图,就无论在何处设置它都无关紧要
答案 2 :(得分:0)
你必须使用 AdapterView.OnItemClickListener。
单击某个项目时将调用此处理程序,并为您提供所单击项目的位置。