0

How can I set a programmatically created checkbox's text to be aligned on the left instead of right side of the checkbox. Below is a code snippet:

Checkbox check1 = new Checkbox(getApplicationContext());
check1.setLayoutParams(new ActionBar.LayoutParams(LinearLayoutCompat.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
check1.setId(fieldNo);
check1.setTextColor(Color.BLACK);
check1.setGravity(Gravity.RIGHT);
check1.setText(formField.get(fieldNo));

The above code resulted in the text shown on the right of the checkbox.

Here is a screenshot : enter image description here

How can I have the text on the left of the checkbox?

Muthukrishnan Rajendran
  • 11,122
  • 3
  • 31
  • 41
max
  • 613
  • 3
  • 13
  • 26

1 Answers1

1

You need to change the following

check1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

In this line you were using ActionBar params and then LinearLayoutCompat params. Try to stick to 1 category and in custom views like checkbox just LinearLayout would do.

UPDATE 1:

You should use CheckedTextView. I have used standard android drawable for that but you can also use your custom Check box design as well.

So your overall code would look like -

final CheckedTextView check1 = new CheckedTextView(getApplicationContext());
    check1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    check1.setId(fieldNo);
    check1.setCheckMarkDrawable(android.R.drawable.checkbox_off_background);
    check1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (check1.isChecked()){
                check1.setChecked(false);
                check1.setCheckMarkDrawable(android.R.drawable.checkbox_off_background);
            }else{
                check1.setChecked(true);
                check1.setCheckMarkDrawable(android.R.drawable.checkbox_on_background);
            }
        }
    });
    check1.setTextColor(Color.BLACK);
    check1.setGravity(Gravity.LEFT);
    check1.setText(formField.get(fieldNo));
Kapil G
  • 4,081
  • 2
  • 20
  • 32
  • I just did and it worked for me absolutely fine. How are you adding this checkbox to your parentView? – Kapil G Jul 29 '17 at 07:11
  • Sorry my bad i misnterpreted your question. I thought you wanted it like in screenshot. – Kapil G Jul 29 '17 at 07:11
  • @max updated my answer and this is working for me now. See if it suits your need. Added an option to add custom drawables as well. – Kapil G Jul 29 '17 at 07:37
  • Thanks I have also added my answer in SO where most of the people look at. Can you please upvote it on this link as well so that next time onward people can have a look at it. https://stackoverflow.com/questions/3156781/how-to-show-android-checkbox-at-right-side – Kapil G Jul 29 '17 at 07:54