如何在Android程序中以编程方式创建CheckedTextView?

5
在安卓中,我正在尝试使用以下方式添加一个CheckTextView:
CheckedTextView checkedtextview = new CheckedTextView(this, null, 
    android.R.attr.listChoiceIndicatorMultiple);
checkedtextview.setText(personobj.lastname + ", " + personobj.firstname);
LocationLayout.addView(checkedtextview);

但是当我测试时,只显示文本,看不到复选框。请问有人知道如何显示复选框吗?
谢谢。
2个回答

10

你忘记设置 CheckedTextView 的选中标记了 - 它默认没有一个。调用以下两种方法之一来设置标记:

  • setCheckMarkDrawable(Drawable d)
  • setCheckMarkDrawable(int resid)

不幸的是,Android的默认选中标记可绘制对象并不在公共命名空间中,因此不能直接访问。不过你可以解析主题的 checkMark 属性并设置它。代码如下:

TypedValue value = new TypedValue();
// you'll probably want to use your activity as context here:
context.getTheme().resolveAttribute(android.R.attr.checkMark, value, true);
int checkMarkDrawableResId = value.resourceId;
// now set the resolved check mark resource id:
checkedtextview.setCheckMarkDrawable(checkMarkDrawableResId);

2
android.R.attr.checkMark 对我没有用,但是使用 android.R.attr.listChoiceIndicatorMultiple 给了我标准的复选框。 - Josh

0
使用setChecked(true)来将其选中。但这不是一个复选框,如果你想要的话,请使用android.widget.CheckBox。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接