实现自定义可检查的relativelayout

时间:2013-05-31 20:51:39

标签: android relativelayout

我希望我的RelativeLayout显示已经过检查。为此,我认为自定义RelativeLayout最简单,即可实现checkable。因此,当我单击一个项目时,将调用它并修改我的布局。我认为最简单的方法是通过setBackgroundColor将其突出显示为选中的全蓝色。

首先,上面有什么问题吗? (这听起来像个好主意吗?)

其次,它的作用是检查一个项目,如果我调用isChecked,它会返回正确的答案。但是,它不会更新RelativeLayout以指示它已被选中。我认为我的代码有问题。

public class CustomRL extends RelativeLayout implements Checkable {

private boolean isChecked;
List<RelativeLayout> rl = new ArrayList<RelativeLayout>();
Context context;

public CustomRL(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
}

@Override
public boolean isChecked() {
    return isChecked;
}

@Override
public void setChecked(boolean isChecked) {
    this.isChecked = isChecked;
    for (RelativeLayout r : rl)
        r.setBackgroundColor(isChecked ? Color.parseColor("#33b5e5")
                : 0x00000000);
}

@Override
public void toggle() {
    this.isChecked = !this.isChecked;
    for (RelativeLayout r : rl)
        r.setBackgroundColor(this.isChecked ? Color.parseColor("#33b5e5")
                : 0x00000000);
}

@Override
protected void onFinishInflate() {
    super.onFinishInflate();
    final int childCount = this.getChildCount();
    for (int i = 0; i < childCount; ++i) {
        getRelativeLayout(this.getChildAt(i));
    }
}

private void getRelativeLayout(View v) {
    if (v instanceof RelativeLayout) {
        rl.add((RelativeLayout) v);
    }
}
}

1 个答案:

答案 0 :(得分:1)

正确使用此布局非常重要。首先,当你在ListView中使用它时,你应该设置

  

listView.setItemsCanFocus(假)

并将选择模式设置为

  

listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE)

  

listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE)