Place a ToggleButton text label for turning it on and off

Anyway, to control the position of the text to turn ToggleButton on and off? For example, I want the text label to stay aligned when it is turned on and right-aligned when turned off.

EDIT: Also, I would include a small addition for the text on the left and right. About 5 dp. and, if possible, finer control over the placement of labels.

ANSWER: This is what I need!

button.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL); button.setPadding(0, 0, 5, 0); 
+6
source share
5 answers
 public class StackActivity extends Activity implements OnCheckedChangeListener { private ToggleButton tb; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tb = (ToggleButton)findViewById(R.id.toggleButton1); tb.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { tb.setGravity(Gravity.LEFT); tb.setPadding(5,0,0,0); // Set left padding } else { tb.setGravity(Gravity.RIGHT); tb.setPadding(0,0,5,0); // Set right padding } } } 
+7
source
 ToggleButton b1 = (ToggleButton) findViewById(R.id.button1); if(b1.isChecked()){ b1.setGravity(Gravity.RIGHT); } else{ b1.setGravity(Gravity.LEFT); } 

Please note that you will not see any changes if the button does not have a minimum size (should be larger than the text as a layout).

+2
source

Since ToggleButton is a subclass of TextView, try using android:gravity="left" .

Please prefer http://developer.android.com/reference/android/widget/TextView.html#attr_android:gravity .

+1
source

Change the alignment by changing gravity whenever a button is pressed, adding some code to the OnClickListener as follows:

 toggleButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (((ToggleButton)v).isChecked()) toggleButton.setGravity(Gravity.LEFT); else toggleButton.setGravity(Gravity.RIGHT); } }); 
+1
source

That's what I need!

 button.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL); button.setPadding(0, 0, 5, 0); 
+1
source

Source: https://habr.com/ru/post/893566/


All Articles