我已经实现了一个 ListView,它的每个元素都包含一个复选框和一个按钮。我为视图编写了一个适配器,如下所示:
public class myadapter extends SimpleAdapter
{
LayoutInflater mLayoutInflater;
public myadapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
{
super(context, data, resource, from, to);
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view = null;
Log.i("xx","getView called: position="+position);
if (convertView != null)
{
view = convertView;
}
else
{
view = mLayoutInflater.inflate(R.layout.custom_row_view, parent, false);
}
Button buttonEdit = (Button) view.findViewById(R.id.editbut);
CheckBox cb = (CheckBox)view.findViewById(R.id.checkbox);
buttonEdit.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
Log.i("xx","Button pressed! position ="+position);
}
});
cb.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1)
{
Log.i("xx","Checkbox changed! position ="+position);
}
});
return super.getView(position, convertView, parent);
}
}
在运行时,如果我单击列表顶行中的按钮,我总是会在日志输出中看到“按下按钮!位置 = 0”。同样,如果我单击复选框,我会看到“复选框已更改!位置 = 0”。如果我单击列表中任何其他元素上的按钮,就会出现问题。有时我会看到正确的日志消息,但有时我什么也看不到。有任何想法吗?
编辑:这是我的 custom_row_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="142dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView android:id="@+id/text1"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#FFFF00"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>
<TextView android:id="@+id/text2"
android:textSize="12sp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>
<TextView android:id="@+id/text3"
android:typeface="sans"
android:textSize="14sp"
android:textStyle="italic"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right" >
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="" />
<Button
android:id="@+id/editbut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Edit" />
</LinearLayout>
</LinearLayout>
</LinearLayout>