Java – How to create a checkedtextview programmatically in Android?

How to create a checkedtextview programmatically in Android?… here is a solution to the problem.

How to create a checkedtextview programmatically in Android?

In android, I tried adding a checktextview:

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

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

Thank you.

Solution

You forgot to set a checkmark for CheckedTextView – it doesn’t 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 drawable is not in Android’s public namespace and is therefore not directly accessible. However, you should be able to parse the theme’s checkMark property and set it. The code for this looks a bit 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);

Related Problems and Solutions