【问题标题】:Android: How to change CheckBox size?Android:如何更改 CheckBox 大小?
【发布时间】:2011-01-10 05:02:17
【问题描述】:

我想让 CheckBox 更小/更大一点,我该怎么做?

【问题讨论】:

    标签: android checkbox


    【解决方案1】:

    从 API 级别 11 开始,存在另一种方法:

    <CheckBox
        ...
        android:scaleX="0.70"
        android:scaleY="0.70"
    />
    

    【讨论】:

    • 此技术还将缩放文本标签。为了弥补这一点,我调整了文本大小如下 checkBox.TextSize = (int)(TEXT_SIZE/SCALE_FACTOR);
    • 如果我这样做是为了增加,例如将它缩放到“2.0”然后它确实变大了,但是图像被剪裁了,我看到了复选框的右半部分和文本的左半部分。有什么办法吗?
    • 很好,但它仍然占用相同的空间。为了解决这个问题,我使用了 -ve 边距,例如:android:layout_marginLeft="-10dp"
    • 我可能不会在 IDE 的预览中显示,但 CheckBox 会在运行时缩放
    • 在我的 AS 设计视图中显示。对不需要修复的东西进行简单修复。我认为 API 或设备会影响。使用 API 22 的 Gennymotion 设备,似乎 0.8 是最高的 Y(水平线性布局),而廉价的 Onix 平板电脑不会剪辑为 1。
    【解决方案2】:

    这是一个更好的解决方案,它不会剪辑和/或模糊可绘制对象,但仅在复选框本身没有文本时才有效(但您仍然可以有文本,只是更复杂,见最后)。

    <CheckBox
        android:id="@+id/item_switch"
        android:layout_width="160dp"    <!-- This is the size you want -->
        android:layout_height="160dp"
        android:button="@null"
        android:background="?android:attr/listChoiceIndicatorMultiple"/>
    

    结果:

    之前使用scaleXscaleY 的解决方案是什么样的:

    您可以通过在其旁边添加一个TextView 并在父布局上添加一个点击侦听器来拥有一个文本复选框,然后以编程方式触发该复选框。

    【讨论】:

    • 如果您的复选框有文字,则使用背景不起作用。
    • @ZachGreen 确实如此。没有想到如果复选框有文本它不起作用的可能性,我没有。将更新答案
    • 这是一个比公认的更好的答案。
    • 在 160dp 时看起来像颗粒状。好像分辨率太低了
    • 如何为此类复选框设置色调?
    【解决方案3】:

    你只需要设置相关的drawable并在checkbox里设置:

    <CheckBox 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:text="new checkbox" 
        android:background="@drawable/my_checkbox_background"
        android:button="@drawable/my_checkbox" />
    

    诀窍在于如何设置可绘制对象。 Here's a good tutorial about this.

    【讨论】:

    • 请记住,不同的设备可能安装了自定义主题。如果您通过放置自己的自定义图像来调整大小,请确保替换应用程序中的每个复选框(即使没有大小更改),否则您最终可能会在某些设备上混合样式。
    • 链接已损坏
    【解决方案4】:

    好吧,我找到了很多答案,但是当我们需要文本时它们也可以在没有文本的情况下正常工作,就像我的 UI 中的复选框一样

    根据我的 UI 要求,我不能不增加 TextSize,所以我尝试的其他选项是 scaleX 和 scaleY(Strach 复选框)以及带有 .png 图像的自定义 xml 选择器(它也会在不同的屏幕尺寸下产生问题)

    但我们有另一个解决方案,那就是 Vector Drawable

    分三步完成。

    第一步:将这三个Vector Drawable复制到你的drawable文件夹中

    checked.xml

    <vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="16dp"
    android:height="16dp"
    android:viewportHeight="24.0"
    android:viewportWidth="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M19,3L5,3c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.11,0 2,-0.9 2,-2L21,5c0,-1.1 -0.89,-2 -2,-2zM10,17l-5,-5 1.41,-1.41L10,14.17l7.59,-7.59L19,8l-9,9z" />
    </vector>
    

    un_checked.xml

    <vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="16dp"
    android:height="16dp"
    android:viewportHeight="24.0"
    android:viewportWidth="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M19,5v14H5V5h14m0,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2V5c0,-1.1 -0.9,-2 -2,-2z" />
    </vector>
    

    (注意如果你在使用 Android Studio,你也可以从那里添加这些 Vector Drawable,右键单击你的 drawable 文件夹然后新建/Vector Asset,然后从那里选择这些drawable)

    第 2 步:为 check_box 创建 XML 选择器

    check_box_selector.xml

    <?xml version="1.0" encoding="utf-8"?>
    
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/checked" android:state_checked="true" />
    <item android:drawable="@drawable/un_checked" />
    </selector>
    

    第 3 步:将该可绘制对象设置为复选框

    <CheckBox
    android:id="@+id/suggectionNeverAskAgainCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:button="@drawable/check_box_selector"
    android:textColor="#FF000000"
    android:textSize="13dp"
    android:text="  Never show this alert again" />
    

    现在是这样的:


    您可以更改其宽度和高度或 viewportHeight 和 viewportWidth 还有fillColor


    希望对您有所帮助!

    【讨论】:

    • 在我的情况下,我必须设置 android:button="@null"android:background="@drawable/check_box_selector" 以使其调整复选框大小。
    • 这种方法会破坏填充
    【解决方案5】:

    我用

    android:scaleX="0.70" android:scaleY="0.70"

    调整复选框的大小

    然后我像这样设置边距

    android:layout_marginLeft="-10dp"
    

    调整复选框的位置。

    【讨论】:

    • 兄弟,虽然它确实缩小了它的大小 - 边距在我的情况下不起作用。我的复选框图像是 173 x 93 - 复选框的大小仍然占据该空间。在我看来,Antoine Bolvy 是一个更灵活的解决方案。
    【解决方案6】:

    这是我做的,第一组:

    android:button="@null"

    还有设置

    android:drawableLeft="@drawable/selector_you_defined_for_your_checkbox"
    

    然后在您的 Java 代码中:

    Drawable d = mCheckBox.getCompoundDrawables()[0];
    d.setBounds(0, 0, width_you_prefer, height_you_prefer);
    mCheckBox.setCompoundDrawables(d, null, null, null);
    

    它对我有用,希望它对你有用!

    【讨论】:

      【解决方案7】:

      更新:这仅适用于 API 17 以后...


      要添加到已经给出的其他出色答案,您只能将复选框设置为文本大小允许的大小。

      根据我对这个问题的回答: - how can we reduce the size of checkbox please give me an idea


      CheckBox 的高度来自 TEXT 和图像。

      在您的 XML 中设置这些属性:

      android:text=""
      android:textSize="0sp"
      

      当然,这仅在您不想要文本时才有效(为我工作)。

      没有这些变化,CheckBox 让我的形象有了很大的优势,正如乔所说的那样

      【讨论】:

        【解决方案8】:

        您可以尝试以下解决方案来更改custom checkbox 的大小,方法是在布局文件中将以下属性设置为Checkbox。为我工作

        android:scaleX="0.8" android:scaleY="0.8"

        android:button="@null"
        android:scaleX="0.8"
        android:scaleY="0.8"
        android:background="@drawable/custom_checkbox"
        

        在可绘制文件中添加以下行

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

        【讨论】:

          【解决方案9】:

          我找不到我想出来的要求的相关答案。因此,此答案适用于带有如下文本的复选框,您希望在其中分别调整可绘制复选框和文本的大小。

          您需要两个 PNG cb_checked.png 和 cb_unchechecked.png 将它们添加到可绘制文件夹中

          现在创建 cb_bg_checked.xml

          <?xml version="1.0" encoding="utf-8"?>
          <layer-list xmlns:tools="http://schemas.android.com/tools"
              xmlns:android="http://schemas.android.com/apk/res/android">
              <item android:drawable="@drawable/cb_checked"
                  android:height="22dp" <!-- This is the size of your checkbox -->
                  android:width="22dp"  <!-- This is the size of your checkbox -->
                  android:right="6dp"   <!-- This is the padding between cb and text -->
                  tools:targetApi="m"
                  tools:ignore="UnusedAttribute" />
          </layer-list>
          

          还有,cb_bg_unchecked.xml

           <?xml version="1.0" encoding="utf-8"?>
              <layer-list xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:tools="http://schemas.android.com/tools">
                  <item android:drawable="@drawable/cb_unchechecked"
                      android:height="22dp" <!-- This is the size of your checkbox -->
                      android:width="22dp"  <!-- This is the size of your checkbox -->
                      android:right="6dp"   <!-- This is the padding between cb and text -->
                      tools:targetApi="m"
                      tools:ignore="UnusedAttribute" />
              </layer-list>
          

          然后创建一个选择器 XML checkbox.xml

          <?xml version="1.0" encoding="utf-8"?>
          <selector xmlns:android="http://schemas.android.com/apk/res/android">
              <item android:drawable="@drawable/cb_bg_checked" android:state_checked="true"/>
              <item android:drawable="@drawable/cb_bg_unchecked" android:state_checked="false"/>
          </selector>
          

          现在像这样定义你的 layout.xml

          <CheckBox
            android:id="@+id/checkbox_with_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:button="@drawable/checkbox"
            android:text="This is text"
            android:textColor="@color/white"
            android:textSize="14dp" /> <!-- Here you can resize text -->
          

          【讨论】:

            【解决方案10】:

            我找到了一种无需创建自己的图像的方法。换句话说,系统映像正在被缩放。我不假装解决方案是完美的。如果有人知道缩短某些步骤的方法,我很乐意了解如何。

            首先,我将以下内容放在项目的主要活动类(WonActivity)中。这是直接取自 Stack Overflow -- 谢谢你们

            /** get the default drawable for the check box */
            Drawable getDefaultCheckBoxDrawable()
            {
              int resID = 0;
            
              if (Build.VERSION.SDK_INT <= 10)
              {
                // pre-Honeycomb has a different way of setting the CheckBox button drawable
                resID = Resources.getSystem().getIdentifier("btn_check", "drawable", "android");
              }
              else
              {
                // starting with Honeycomb, retrieve the theme-based indicator as CheckBox button drawable
                TypedValue value = new TypedValue();
                getApplicationContext().getTheme().resolveAttribute(android.R.attr.listChoiceIndicatorMultiple, value, true);
                resID = value.resourceId;
              }
            
              return getResources().getDrawable(resID);
            }
            

            其次,我创建了一个类来“缩放可绘制对象”。请注意,它与标准的 ScaleDrawable 完全不同。

            import android.graphics.drawable.*;
            
            /** The drawable that scales the contained drawable */
            
            public class ScalingDrawable extends LayerDrawable
            {
              /** X scale */
              float scaleX;
            
              /** Y scale */
              float scaleY;
            
              ScalingDrawable(Drawable d, float scaleX, float scaleY)
              {
                super(new Drawable[] { d });
                setScale(scaleX, scaleY);
              }
            
              ScalingDrawable(Drawable d, float scale)
              {
                this(d, scale, scale);
              }
            
              /** set the scales */
              void setScale(float scaleX, float scaleY)
              {
                this.scaleX = scaleX;
                this.scaleY = scaleY;
              }
            
              /** set the scale -- proportional scaling */
              void setScale(float scale)
              {
                setScale(scale, scale);
              }
            
              // The following is what I wrote this for!
            
              @Override
              public int getIntrinsicWidth()
              {
                return (int)(super.getIntrinsicWidth() * scaleX);
              }
            
              @Override
              public int getIntrinsicHeight()
              {
                return (int)(super.getIntrinsicHeight() * scaleY);
              }
            }
            

            最后,我定义了一个复选框类。

            import android.graphics.*;
            import android.graphics.drawable.Drawable;
            import android.widget.*;
            
            /** A check box that resizes itself */
            
            public class WonCheckBox extends CheckBox
            {
              /** the check image */
              private ScalingDrawable checkImg;
            
              /** original height of the check-box image */
              private int origHeight;
            
              /** original padding-left */
              private int origPadLeft;
            
              /** height set by the user directly */
              private float height;
            
              WonCheckBox()
              {
                super(WonActivity.W.getApplicationContext());
                setBackgroundColor(Color.TRANSPARENT);
            
                // get the original drawable and get its height
                Drawable origImg = WonActivity.W.getDefaultCheckBoxDrawable();
                origHeight = height = origImg.getIntrinsicHeight();
                origPadLeft = getPaddingLeft();
            
                // I tried origImg.mutate(), but that fails on Android 2.1 (NullPointerException)
                checkImg = new ScalingDrawable(origImg, 1);
                setButtonDrawable(checkImg);
              }
            
              /** set checkbox height in pixels directly */
              public void setHeight(int height)
              {
                this.height = height;
                float scale = (float)height / origHeight;
                checkImg.setScale(scale);
            
                // Make sure the text is not overlapping with the image.
                // This is unnecessary on Android 4.2.2, but very important on previous versions.
                setPadding((int)(scale * origPadLeft), 0, 0, 0);
            
                // call the checkbox's internal setHeight()
                //   (may be unnecessary in your case)
                super.setHeight(height);
              }
            }
            

            就是这样。如果您在视图中放置一个 WonCheckBox 并应用 setHeight(),则复选框图像的大小将是正确的。

            【讨论】:

              【解决方案11】:

              使用此代码。

              在布局中:

              <CheckBox
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:button="@drawable/my_checkbox"  *** here
                      android:checked="true"/>
              

              添加一个新的drawable:my_checkbox.xml

              <?xml version="1.0" encoding="utf-8"?>
              <selector xmlns:android="http://schemas.android.com/apk/res/android">
              
              <item
                  android:state_checked="false"
                  android:drawable="@drawable/checkbox_off_background"/>
              
              <item
                  android:state_checked="true"
                  android:drawable="@drawable/checkbox_on_background"/>
              

              最后创建 2 个可绘制对象:

              checkbox_off_background.xml

              <?xml version="1.0" encoding="utf-8"?>
              <layer-list
                  xmlns:android="http://schemas.android.com/apk/res/android">
              
              <item>
                  <shape android:shape="rectangle">
                      <size
                          android:height="25dp"   *** your size
                          android:width="25dp"/>
                  </shape>
              </item>
              
              <item android:drawable="@android:drawable/checkbox_off_background"/>
              

              还有 checkbox_on_background.xml

              <?xml version="1.0" encoding="utf-8"?>
              <layer-list
                  xmlns:android="http://schemas.android.com/apk/res/android">
              
              <item>
                  <shape android:shape="rectangle">
                      <size
                          android:height="25dp"
                          android:width="25dp"/>
                  </shape>
              </item>
              
              <item android:drawable="@android:drawable/checkbox_on_background"/>
              

              【讨论】:

                【解决方案12】:

                假设您的原始 xml 是:

                <?xml version="1.0" encoding="utf-8"?>
                <selector xmlns:android="http://schemas.android.com/apk/res/android">
                    <item android:state_checked="true"
                        android:drawable="@drawable/tick_img" />
                    <item android:state_checked="false"
                        android:drawable="@drawable/untick_img" />
                </selector>
                

                然后只需删除复选框 xml 中的 android:button="@drawable/xml_above",并在 java 中以编程方式进行可绘制缩放(将 150 大尺寸减小到所需的 dp):

                CheckBox tickRememberPasswd = findViewById(R.id.remember_tick);
                
                //custom selector size
                Drawable drawableTick = ContextCompat.getDrawable(this, R.drawable.tick_img);
                Drawable drawableUntick = ContextCompat.getDrawable(this, R.drawable.untick_img);
                Bitmap bitmapTick = null;
                if (drawableTick != null && drawableUntick != null) {
                    int desiredPixels = Math.round(convertDpToPixel(150, this));
                
                    bitmapTick = ((BitmapDrawable) drawableTick).getBitmap();
                    Drawable dTick = new BitmapDrawable(getResources()
                            , Bitmap.createScaledBitmap(bitmapTick, desiredPixels, desiredPixels, true));
                
                    Bitmap bitmapUntick = ((BitmapDrawable) drawableUntick).getBitmap();
                    Drawable dUntick = new BitmapDrawable(getResources()
                            , Bitmap.createScaledBitmap(bitmapUntick, desiredPixels, desiredPixels, true));
                
                    final StateListDrawable statesTick = new StateListDrawable();
                    statesTick.addState(new int[] {android.R.attr.state_checked},
                            dTick);
                    statesTick.addState(new int[] { }, //else state_checked false
                            dUntick);
                    tickRememberPasswd.setButtonDrawable(statesTick);
                }
                

                convertDpToPixel 方法:

                public static float convertDpToPixel(float dp, Context context) {
                    Resources resources = context.getResources();
                    DisplayMetrics metrics = resources.getDisplayMetrics();
                    float px = dp * (metrics.densityDpi / 160f);
                    return px;
                }
                

                【讨论】:

                  【解决方案13】:

                  如果您想在复选框中添加自定义图像,那么 将按钮设置为空,只需将背景添加到复选框 解决了

                   <CheckBox
                      android:layout_width="22dp"
                      android:layout_height="22dp"
                      android:layout_marginLeft="-10dp"
                      android:button="@null"
                      android:background="@drawable/memory_selector"/>
                  

                  【讨论】:

                    猜你喜欢
                    • 2014-05-02
                    • 2020-04-19
                    • 2011-03-02
                    • 1970-01-01
                    • 1970-01-01
                    • 2019-12-31
                    • 2023-04-02
                    • 2019-12-05
                    相关资源
                    最近更新 更多