我有一个由每行中的文本和按钮组成的列表视图。我必须为驻留在行中的每个按钮实现单击侦听器,但我无法这样做。我也检查了与 SO 不同的地方,但无法得到想要的结果。为此,我将自定义适配器实现为:
public class CategoryAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mInflater;
String[] strings = { "jjacj", "kpomkn", "jjbjbj nk", "njbhvh",
"mknkn", "mnknlhn", "lknkn", "mknkn"};
Holder holder = null;
public CategoryAdapter(Context context) {
this.mContext = context;
}
@Override
public int getCount() {
return strings.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return 0;
}
@SuppressWarnings("static-access")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
mInflater = (LayoutInflater) mContext
.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
holder = new Holder();
convertView = mInflater.inflate(R.layout.layout_child_category,
null);
holder.mTxtTitle = (TextView) convertView
.findViewById(R.id.txt_notification);
holder.mButtonTag = (Button) convertView
.findViewById(R.id.btnNotify);
holder.mLayoutMain = (RelativeLayout) convertView
.findViewById(R.id.layout_main);
// convertView.setOnClickListener(callback);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.mTxtTitle.setText(strings[position]);
holder.mButtonTag.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btnSelection();
}
});
if (position == 0) {
holder.mLayoutMain.setBackgroundResource(R.drawable.bg_table_top);
} else if (position == getCount() - 1) {
holder.mLayoutMain
.setBackgroundResource(R.drawable.bg_table_bottom);
} else {
holder.mLayoutMain
.setBackgroundResource(R.drawable.bg_table_middle);
}
return convertView;
}
OnClickListener callback = new OnClickListener() {
@Override
public void onClick(View v) {
btnSelection();
}
};
private void btnSelection() {
if (holder.mButtonTag.getTag().equals("no")) {
holder.mButtonTag.setTag("yes");
holder.mButtonTag.setText("NEI");
holder.mButtonTag.setPadding(20, 0, 0, 0);
holder.mButtonTag.setBackgroundResource(R.drawable.ic_btn_nei);
holder.mButtonTag.setTextColor(Color.BLACK);
} else {
holder.mButtonTag.setTag("no");
holder.mButtonTag.setText("JA");
holder.mButtonTag.setPadding(0, 0, 20, 0);
holder.mButtonTag.setBackgroundResource(R.drawable.ic_btn_ja);
holder.mButtonTag.setTextColor(Color.WHITE);
}
}
static class Holder {
Button mButtonTag;
TextView mTxtTitle;
RelativeLayout mLayoutMain;
}
}
列出子布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_main"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="@drawable/bg_table_middle" >
<TextView
android:id="@+id/txt_notification"
style="@style/textview_layout"
android:textColor="@android:color/black" />
<Button
android:id="@+id/btnNotify"
style="@style/button_layout" />
</RelativeLayout>
这是我的看法:
任何人都可以让我知道我缺少的地方,或者应该做任何更改以在列表中的每个按钮上至少祝酒。任何形式的帮助将不胜感激。
谢谢。