Removing padding from toggle button in Android

孤者浪人 提交于 2019-12-20 19:49:20

问题


I am creating a simple toggle button in android and setting background as a drawable.

<ToggleButton
    android:layout_width="wrap_content"
    android:drawablePadding="0dp"
    android:layout_height="wrap_content"
    android:text=""
    android:textSize="12sp"
    android:padding="0dp"
    android:id="@+id/tag_text"
    android:background="@drawable/toggle_selector"/>

toggle_selector.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/toggle_button_off" android:state_checked="false"/>
    <item android:drawable="@drawable/toggle_button_on" android:state_checked="true"/>
</selector>

toggle_button_off and toggle_button_on have simple shape drawable with some color.

And this is how I am inflating this toggle button into my view:

View child = getLayoutInflater().inflate(R.layout.tags, null);
        ToggleButton tag = ((ToggleButton)child.findViewById(R.id.tag_text));
        tag.setText("Testing");
        tag.setTextOff("Testing");
        tag.setTextOn("Testing");
        flowlayout.addView(child);

The problem is there is just too much padding around the text in toggle button and I am not able to get rid of it by setting padding = "0dp". Text on these buttons are dynamically added so setting a constant height weight is not helping too.


回答1:


I got the solution by setting minWidth, minHeight to 0dp. Wrapping content in the width and height. And then adding the custom padding to togglebutton that I want.

<ToggleButton
    android:layout_width="wrap_content"
    android:minWidth="0dp"
    android:minHeight="0dp"
    android:layout_height="wrap_content"
    android:text=""
    android:textSize="12sp"
    android:padding="2dp"
    android:id="@+id/tag_text"
    android:background="@drawable/toggle_selector"/>



回答2:


Use CheckedTextView instead:

 final CheckedTextView toggle = new CheckedTextView(clipboardWordsLayout.getContext());
 toggle.setText(kanji);
 final int min = Views.dp2px(48, clipboardWordsLayout.getContext());
 toggle.setMinimumWidth(min);
 toggle.setMinimumHeight(min);
 toggle.setGravity(Gravity.CENTER);
 toggle.setBackgroundResource(R.drawable.togglebutton);
 toggle.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         toggle.setChecked(!toggle.isChecked());
     }
 });


来源:https://stackoverflow.com/questions/29911613/removing-padding-from-toggle-button-in-android

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