问题
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
withAppCompatButton
,TextView
withAppCompatTextView
, 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