omega
omega

Reputation: 43913

How to create a checkedtextview in android programatically?

In android I am trying to add a checktextview using this:

CheckedTextView checkedtextview = new CheckedTextView(this, null, 
    android.R.attr.listChoiceIndicatorMultiple);
checkedtextview.setText(personobj.lastname + ", " + personobj.firstname);
LocationLayout.addView(checkedtextview);

But when I test this, it only shows the text and I don't see the checkbox. Does anyone know how to display the checkbox?

Thanks.

Upvotes: 5

Views: 3441

Answers (2)

MH.
MH.

Reputation: 45503

You forgot to set the checkmark drawable to the CheckedTextView - it doesn't have one by default. Call one of the following two methods on the view to set one:

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

Unfortunately the default checkmark drawables are not in Android's public name space, and thus not directly accessible. You should be able to resolve the theme's checkMark attribute though and set that. The code to do so would look somewhat like this:

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);

Upvotes: 11

Gabe Sechan
Gabe Sechan

Reputation: 93678

Use setChecked(true) to make it checked. But this isn't a checkbox, if you want that use android.widget.CheckBox instead.

Upvotes: 0

Related Questions