我输入了这一行:lv1.setOnItemClickListener((OnItemClickListener)this);因为它会产生一条红色的波浪线。 我是否正确使用onItemClick功能?
public class MainActivity extends Activity {
private ListView lv1;
private String lv_arr[] = {
"Android",
"iPhone",
"Blackberry",
"AndroidPeople"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setOnItemClickListener((OnItemClickListener) this);
//by using setAdapter method in ListView, we can add string array in list
lv1.setAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, lv_arr));
}
public void onItemClick(AdapterView arg0, View v, int position, long arg3){
Toast.makeText(this, "You clicked" + lv_arr[position], Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:1)
您的MainActivity
没有实施OnItemClickListener
,这就是为什么它会给您“红色线条”。
您应该将类声明更改为:
public class MainActivity extends Activity implements OnItemClickListener {
这意味着,在将MainActivity
设置为OnItemClickListener
ListView
投射到{{1}}
答案 1 :(得分:0)
你需要实现OnItemClickListener,或者只是你可以编写
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(this, "You clicked" + lv_arr[position], Toast.LENGTH_LONG).show();
}
});
答案 2 :(得分:0)
如果您尝试使用自定义onClickListener()
的每一行,则需要扩展ArrayAdapter
(例如)并为其中的每一行实施onClickListener()
getView()
方法。
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// Speaking very vaguely, convertView represents each of your rows
if (convertView == null) {
...
convertView.setOnClickListener(new View.OnClickListener() {
public void onClick(final View v) {
// Whetever you need
...
}
}
});
else
...
// Rest of your implementation
...
return convertView;
}