我正在尝试使用自定义适配器和列表视图设置来设置 onItemClickListener。似乎无法让听众工作。我认为我没有正确设置它。任何帮助表示赞赏。非常感谢。
适配器:
public class ModuleAdapter extends ArrayAdapter<Module> {
Context context;
int layoutResourceId;
Module data[];
public ModuleAdapter(Context context, int layoutResourceId,
Module data[]) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ModuleHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ModuleHolder();
holder.modJapTitle = (TextView)row.findViewById(R.id.moduleJapTitle);
holder.modEngTitle = (TextView)row.findViewById(R.id.moduleEngTitle);
holder.modComp = (TextView)row.findViewById(R.id.moduleCompletion);
holder.modRating = (RatingBar)row.findViewById(R.id.moduleScore);
row.setTag(holder);
}
else
{
holder = (ModuleHolder)row.getTag();
}
Module module = data[position];
holder.modJapTitle.setText(module.moduleJapaneseTitle);
holder.modEngTitle.setText(module.moduleEnglishTitle);
holder.modComp.setText(module.moduleCompletionRate);
holder.modRating.setRating(module.moduleRating);
return row;
}
static class ModuleHolder
{
TextView modEngTitle;
TextView modJapTitle;
TextView modComp;
RatingBar modRating;
}
}
执行:
ModuleAdapter moduleData = new ModuleAdapter(this, R.layout.module_box_item, module_data);
ListView listView1 = (ListView)findViewById(R.id.moduleListContainer);
listView1.setAdapter(moduleData);
listView1.setCacheColorHint(Color.TRANSPARENT);
listView1.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.v("Module Item Trigger", "Module item was triggered");
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_SHORT).show();
}
});
这里也是列表中单个项目之一的 XML 布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/moduleBox"
android:id="@+id/moduleBoxSingle" >
<TextView
android:id="@+id/moduleJapTitle"
style="@style/moduleTitleJap" />
<TextView
android:id="@+id/moduleCompletion"
android:layout_above="@+id/moduleSepartor"
style="@style/moduleCompletion" />
<View
android:id="@+id/moduleSepartor"
android:layout_below="@+id/moduleJapTitle"
style="@style/moduleSeperator" />
<TextView
android:id="@+id/moduleEngTitle"
android:layout_below="@+id/moduleSepartor"
style="@style/moduleTitleEng" />
<RatingBar
android:id="@+id/moduleScore"
android:layout_below="@+id/moduleSepartor"
style="@style/moduleRating"
android:layout_alignParentRight="true" />
</RelativeLayout>