我对Java很新,对listviews几乎没有经验。我已经能够使用自定义列表适配器将项目成功添加到列表视图中。但是,我现在想要在触摸每个项目时执行操作。
触摸列表项时,我无法获取OnItemClickListener事件,我不确定问题出在哪里。
代码:
public class FragmentA extends Fragment implements OnItemClickListener{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_a, container, false);
ListView listView = (ListView)V.findViewById(R.id.list);
getData data = getData.getMyData();
CustomList adapter = new
CustomList(getActivity(), data.Headline.toArray(new String[data.Headline.size()]), data.Description.toArray(new String[data.Description.size()]), data.imageId.toArray(new Integer[data.imageId.size()]));
listView.setAdapter(adapter);
return V;
}
public void onItemClickListener(AdapterView<?> parent, View view, int position, long id)
{
Log.e("CLICKED","CLICKED");
}
}
如果有帮助,这里是自定义适配器类的代码:
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] titleId;
private final String[] descriptionId;
private final Integer[] pictureid;
public CustomList(Activity context,
String[] Headline, String[] Description, Integer[] imageId) {
super(context, R.layout.single_row, Headline);
this.context = context;
this.titleId = Headline;
this.descriptionId = Description;
this.pictureid = imageId;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.single_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvTitle);
TextView txtDescription = (TextView) rowView.findViewById(R.id.tvDescription);
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivIcon);
txtTitle.setText(titleId[position]);
txtDescription.setText(descriptionId[position]);
imageView.setImageResource(pictureid[position]);
return rowView;
}
}
答案 0 :(得分:0)
将侦听器设置为ListView:
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("CLICKED","CLICKED");
}
});
答案 1 :(得分:0)
您必须使用listView.setOnItemClickListener将回调链接到视图。
您可以执行以下操作:
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,int pos, long id) {
//Your code here
}
});
但是,在您的情况下,由于活动已经实现了OnItemClickListener(),您可以简单地:
listView.setOnItemClickListener(this);