ToggleButton Text Label Placement for On and Off State

时光毁灭记忆、已成空白 提交于 2019-12-18 16:52:41

问题


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 off.

EDIT: Also, I'd to include a little padding for the text on the left and right. About 5dp. and have finer control over the label placement if possible.

ANSWER: This is what I needed!

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

回答1:


  
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
        }
    }
}



回答2:


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).




回答3:


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.




回答4:


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);
            }
        });



回答5:


This is what I needed!

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


来源:https://stackoverflow.com/questions/6827437/togglebutton-text-label-placement-for-on-and-off-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!