public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_campaign_list);
Campaign campaign_data[] = new Campaign[]
{
new Campaign(R.drawable.hlbb, "MSIG HLBB PA Extra"),
new Campaign(R.drawable.hlbb, "MSIG HLBB SSP Plus")
};
CampaignAdapter adapter = new CampaignAdapter(this, R.layout.listview_header_row, campaign_data);
listView1 = (ListView)findViewById(R.id.listView1);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
我可以在没有setonitemclicklistener函数的情况下运行上面的代码,当我添加setOnItemClickListener时,它停止工作。错误是什么?我是Android..Thx的新手
答案 0 :(得分:0)
I don't know how is your CampaignAdapter code, but you are trying to cast the row view which you are inflating into TextView. You should use your adapter to access the item using the position of element:
CampaignAdapter adapter = new CampaignAdapter(this, R.layout.listview_header_row, campaign_data);
listView1 = (ListView)findViewById(R.id.listView1);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Campaign item = (Campaign) adapter.getItem(position);
// Now you can access to the campaing value that you want
// For instance, item.getText()
Toast.makeText(getBaseContext(), item.getText(), Toast.LENGTH_LONG).show();
}
});