Android checkboxes added by code don't have the right appearance?

白昼怎懂夜的黑 提交于 2019-12-31 03:49:09

问题


I've got a really basic app in which I'm trying to insert dynamic checkboxes, and I can get them to appear, but they're not showing with the correct styling.

See below - Foo is in the LinearLayout by definition; Bar is being added programmatically. Foo is showing with a grey box for the check, Bar is showing with a white box.

Link to image...

Here's the code that's creating these:

for (Integer i=0; i < arArray.length;i++) {
    CheckBox cb = new CheckBox(getApplicationContext());
    cb.setText("Bar");
    cb.setTextColor(getResources().getColor(android.R.color.black));
    cb.setOnCheckedChangeListener(clListener);
    llDeckChecks.addView(cb);
}

I've tried setting the drawable to some android.R.drawable types, but nothing matches the Foo checkbox, so I'm entirely stumped at this point.


回答1:


You should use the activity context to create the button instead of the application context. If you use getApplicationContext() it does not extend ContextThemeWrapper.

Try changing

CheckBox cb = new CheckBox(getApplicationContext());

to

CheckBox cb = new CheckBox(YourActivity.this); // or getActivity() if in a fragment.



回答2:


AppCompat replaces the default widgets with tinted, consistent styles, as mentioned in the Android Support Library 22.1 blog post:

This is done automatically when inflating layouts - replacing Button with AppCompatButton, TextView with AppCompatTextView, etc. to ensure that each could support tinting.

If you'd like to create these programmatically, you can use AppCompatCheckBox in place of Checkbox in your code, passing in your current Context such as your AppCompatActivity.

Note: it is very important to not use getApplicationContext() as it does not have the styling information required.




回答3:


Use cb.setButtonDrawable(R.drawable.cbOutline); where "cbOutline" is your drawable for the checkboxes outline you defined in your XML.



来源:https://stackoverflow.com/questions/32365847/android-checkboxes-added-by-code-dont-have-the-right-appearance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!