我正在使用可扩展列表,如下所示:

Expandable列表活动有一个名为"OnGroupExpand"的方法,它允许您在父项展开之前执行一些工作,并且它的子项被公开.
在我的情况下,我想将checkChangeHandler附加到每个孩子的复选框,这样当它被点击时,我可以将孩子标记为完整.我有列表显示,子窗口显示父级扩展,但我的复选框什么也没做.
然后,我尝试在"onGroupExpand"方法中动态添加复选框处理程序.但是,当触发onGroupExpand时,我在尝试获取对每个子视图的引用时会收到非法的强制转换异常.
public void onGroupExpand (int groupPosition) {
int numOfChildren = expListAdapter.getChildrenCount(groupPosition);
for(int i = 0; i < numOfChildren; i++)
{
//Get exception here because getChild() returns Object - but how else can
//can I attach a check box to each child?
View v = (View) expListAdapter.getChild(groupPosition, i);
CheckBox cb = (CheckBox)v.findViewById( R.id.checkComplete );
cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
Toast.makeText(getBaseContext(), "Check Changed for " + groupPosition, 2000);
}
});
}
Run Code Online (Sandbox Code Playgroud)
我的主要问题是获取对Child视图的引用,以便我可以动态附加处理程序.请参阅我正在尝试执行此操作的代码注释.谢谢你的时间...
我相信问题在于
View v = (View) expListAdapter.getChild(groupPosition, i);
Run Code Online (Sandbox Code Playgroud)
不返回a View但返回该位置的数据.您可能正在使用字符串或prefs对象或其他内容.您将获得它的底层对象,您可以对该对象进行更改.当在下面的方法中创建视图(并且由ListView自动调用)时,您可以设置任何onCheckChanged侦听器:
abstract View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
Run Code Online (Sandbox Code Playgroud)
添加示例代码
以下是执行您想要执行的操作的示例适配器.视图是在适配器上创建的,而不是活动.我假设您在Activity中创建了一个SimpleExpandableListAdapter.而不是那样,添加以下类并创建该视图.
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SimpleExpandableListAdapter;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class ExampleAdapter extends SimpleExpandableListAdapter {
protected Context mContext;
public ExampleAdapter(ExampleActivity exampleActivity, List createGroupList, int groupRow, String[] strings, int[] is, List createChildList, int childRow, String[] strings2, int[] is2) {
super(exampleActivity, createGroupList, groupRow, strings, is, createChildList, childRow, strings2, is2);
mContext = exampleActivity;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View v = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
if (v != null) {
final String value = "Check Changed for " + groupPosition + " " + childPosition;
CheckBox cb = (CheckBox)v.findViewById( R.id.checkComplete );
cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
Toast toast = Toast.makeText(mContext, value, 2000);
toast.show();
}
});
}
return v;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1973 次 |
| 最近记录: |