Search code examples
androidxmlcheckboxandroid-appwidgetandroid-checkbox

AppCompatCheckBox not working for below API 21


I created a dynamic checkbox with the following code:

xml:

<LinearLayout
    android:id="@+id/layout_checkbox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">


</LinearLayout>

java:

LinearLayout ll = (LinearLayout) findViewById(R.id.layout_checkbox);

ll.removeAllViews();

for (int i = 0; i < 10; i++) {

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    AppCompatCheckBox myCheckBox = new AppCompatCheckBox(getApplicationContext());
    myCheckBox.setText(i);
    myCheckBox.setTextColor(Color.parseColor("#FFFFFF"));
    myCheckBox.setHintTextColor(Color.parseColor("#FFFFFF"));
    myCheckBox.setTextSize(12);

    myCheckBox.setId(i);

    ll.addView(myCheckBox, lp);
}

Now from above code only LOLLIPOP version shows the checkbox with text. And for below LOLLIPOP version it shows only Text but not showing the checkbox.

Same thing work with all device if I put the below code in xml file:

<android.support.v7.widget.AppCompatCheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Testing"
    android:buttonTint="@color/colorAccent"/>

But I can't define the checkbox in xml as I have to create it dynamically.

Even setButtonTintList is not working for below LOLLIPOP

How can I show the Checkbox for below LOLLIPOP version with AppCompatCheckBox ?


Solution

  • Do not use getApplicationContext(), for the Context passed in to new AppCompatCheckBox() you need to use a reference to your activity (that extends AppCompatActivity) context for it to correctly inject the styling for the AppCompatCheckBox. This will be new AppCompatCheckBox(this) if you're creating this in an activity, or new AppCompatCheckBox(getActivity()) if you're creating this in a fragment.

    Code like this below will work on all versions:

    public class MainActivity extends AppCompatActivity {
    
      @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
        for (int i = 0; i < 10; i++) {
          LinearLayout.LayoutParams lp =
              new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    
          AppCompatCheckBox myCheckBox = new AppCompatCheckBox(this);
          myCheckBox.setText("text");
          myCheckBox.setTextSize(12);
    
          myCheckBox.setId(i);
    
          layout.addView(myCheckBox, lp);
        }
      }
    
    }