Is there anyway to control the text position for a ToggleButton\'s on and off state? For instance, I want the text label to be left aligned when on and right aligned when of
This is what I needed!
button.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
button.setPadding(0, 0, 5, 0);
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
}
}
}
Since ToggleButton is a subclass of TextView, try to use android:gravity="left"
.
Please prefer to http://developer.android.com/reference/android/widget/TextView.html#attr_android:gravity.
ToggleButton b1 = (ToggleButton) findViewById(R.id.button1);
if(b1.isChecked()){
b1.setGravity(Gravity.RIGHT);
}
else{
b1.setGravity(Gravity.LEFT);
}
Note, that you will not see any changes if the button is not of a minimum size (has to be bigger than the lable text).
Change the alignment by changing the gravity whenever the button is clicked by adding some code in the OnClickListener like this:
toggleButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
if (((ToggleButton)v).isChecked())
toggleButton.setGravity(Gravity.LEFT);
else
toggleButton.setGravity(Gravity.RIGHT);
}
});