我的列表视图行有自定义布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/listSelector"
android:orientation="horizontal">
<LinearLayout
android:id="@+id/checkboxSelection1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip">
<CheckBox android:id="@+id/checkbox1" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/checkbox1"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
我还有一个适配器来显示相应的数据;它做的。从UI的角度来看,它看起来像我想要它。
然而,当我点击一个复选框时 - 没有任何反应。我想存储我在后端选择的项目列表(理想情况下在活动类中)。
在我的活动课中的onCreate中,我有这段代码:
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// Click event for single list row
listView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
int i = 1;
}
});
我得到了int 1 = 1;在那里,我可以添加一个断点,看看它是否被击中。它没有。我确定我做错了,就像它连接到列表视图行而不是复选框或其他东西 - 但我不确定如何将事件挂钩到复选框。
如果有人能指出我正确的方向,我会很感激。
由于
我在适配器中有这个:
taskChecked.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton arg0, boolean arg1)
{
// TODO Auto-generated method stub
int i = 1;
}
});
那个断点确实受到了打击。所以我只是试图找出当选中或取消选中复选框时,如何在活动中引发事件,而不仅仅是适配器。
答案 0 :(得分:2)
不要这样做!我几乎疯了,试图在ListView中获取小部件来响应点击。不要将Button,ImageButton或CheckBox小部件放在ListView中。 TextViews和ImageViews是最佳选择。试图对该CheckBox上的单击做出反应,找到它所在的ListView项目,然后向Activity发送一些内容可能对您的健康非常有害。我试过了。
TextView + ImageView可以在显示复选标记的图标和不显示复选标记的图标之间变化 - 模拟CheckBox;
ImageView本身可以模拟一个Button。
需要将ImageView设置为focus = false。
首先,创建一个新类,其中包含要为ListView中的每个项显示的字段。我创建了一个显示的文本和一个指示是否已检查的布尔值。将此类用于ArrayList和ArrayAdapter。
然后为ListView添加setOnItemClickListener(),然后使用position查找项目视图,然后获取新类的项目并切换其布尔值。
在MyArrayAdapter.getView方法中,getItem(position)返回该项的新类的实例。使用布尔值确定要用于ImageView的图标。
当您需要知道ListView中的“已检查”和“未检查”时,您只需浏览ArrayList并检查每个项目的布尔值。
答案 1 :(得分:1)
我明白了。
在适配器中我添加了这个: 使用_activity是从调用活动传递到构造函数的活动。根据getView中的位置和构造适配器时传入的数据,myObj被声明为代码中的最后一个。
taskChecked.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton button, boolean checked)
{
// Cast it so we can access the public functions
MyActivity myActivity = (MyActivity) _activity;
if (checked) // true if the checkbox is checked, false if unchecked
{
myActivity.checkboxSelected(myObj);
}
}
});
在活动中我添加了这个:
public void checkboxSelected(MyObj myObj)
{
// Do stuff with myObj here
}
希望这有助于某人。