Android : CheckBox 크기를 변경하는 방법은 무엇입니까?
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" />
트릭은 드로어 블을 설정하는 방법입니다. 이것에 대한 좋은 튜토리얼이 있습니다.
API 레벨 11부터 다른 접근 방식이 있습니다.
<CheckBox
...
android:scaleX="0.70"
android:scaleY="0.70"
/>
드로어 블을 자르거나 흐리게 처리하지 않는 더 나은 솔루션이 있습니다.하지만 체크 박스 자체에 텍스트가없는 경우에만 작동합니다 (하지만 여전히 텍스트를 가질 수 있습니다. 더 복잡합니다. 끝 부분 참조).
<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"/>
결과:
이전 솔루션의 모습 scaleX과 scaleY모습 :
TextView옆에를 추가하고 상위 레이아웃에 클릭 리스너를 추가 한 다음 프로그래밍 방식으로 확인란을 트리거하여 텍스트 확인란을 만들 수 있습니다 .
글쎄요 많은 답변을 찾았지만 UI와 같은 확인란이있는 텍스트가 필요할 때 텍스트없이 잘 작동합니다.
여기 내 UI 요구 사항에 따라 TextSize를 늘릴 수 없으므로 시도한 다른 옵션은 scaleX 및 scaleY (확인란 선택) 및 .png 이미지가있는 사용자 정의 xml 선택기입니다 (화면 크기가 다른 문제도 생성)
하지만이를위한 또 다른 솔루션이 있습니다. 바로 Vector Drawable입니다.
3 단계로 진행합니다.
1 단계 : Vector 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로 작업하는 경우 이러한 벡터 드로어 블 양식을 거기에 추가 할 수도 있습니다. 드로어 블 폴더를 마우스 오른쪽 버튼으로 클릭 한 다음 여기에서 드로어 블을 선택하는 New / Vector Asset ) 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:scaleX="0.70" android:scaleY="0.70"
확인란의 크기를 조정하려면
그런 다음 여백을 이렇게 설정합니다
android:layout_marginLeft="-10dp"
확인란의 위치를 조정합니다.
내가 한 일은 다음과 같습니다.
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);
저에게도 효과가 있으며, 여러분에게도 효과가 있기를 바랍니다!
업데이트 : 이것은 API 17 이상에서만 작동합니다 ...
이미 주어진 다른 훌륭한 답변에 추가하려면 확인란을 텍스트 크기가 허용하는만큼 작게 만들 수 있습니다.
이 질문에 대한 내 대답에 따르면- 확인란 크기를 어떻게 줄일 수 있습니까?
CheckBox TEXT와 이미지에서 높이를 가져옵니다.
XML에서 다음 속성을 설정합니다.
android:text=""
android:textSize="0sp"
물론 이것은 당신이 텍스트를 원하지 않는 경우에만 작동합니다 (저를 위해 일했습니다).
이러한 변경 없이는 CheckBoxJoe가 언급했듯이 내 이미지 주변에 큰 차이를주었습니다.
자신의 이미지를 만들지 않고 할 수있는 방법을 찾았습니다. 즉, 시스템 이미지의 크기가 조정되고 있습니다. 나는 해결책이 완벽한 척하지 않습니다. 단계를 단축하는 방법을 아는 사람이 있으면 기꺼이 방법을 찾을 수 있습니다.
먼저 프로젝트의 주 액티비티 클래스 (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 ()를 적용하면 확인란 이미지가 올바른 크기가됩니다.
이 코드를 사용하십시오.
레이아웃 :
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/my_checkbox" *** here
android:checked="true"/>
새로운 드로어 블 추가 : 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"/>
또한 체크 박스 _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"/>
원본 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>
그런 다음 android:button="@drawable/xml_above"확인란 xml에서 제거 하고 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;
}
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>
내 요구 사항에 대한 관련 답변을 찾을 수 없었습니다. 따라서이 답변은 체크 박스 드로어 블과 텍스트의 크기를 개별적으로 조정하려는 아래와 같은 텍스트가있는 체크 박스에 대한 것입니다.
두 개의 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 확인란을 만듭니다.
<?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 -->
참고 URL : https://stackoverflow.com/questions/2151241/android-how-to-change-checkbox-size
'Programing' 카테고리의 다른 글
| 텍스트 상자에 빈 값이 있는지 확인 (0) | 2020.09.13 |
|---|---|
| 직렬화 가능한 객체를 파일에 저장 / 복원하는 방법은 무엇입니까? (0) | 2020.09.13 |
| Picasso (Android)로드 완료 이벤트를 수신하는 방법은 무엇입니까? (0) | 2020.09.13 |
| numpy에서 1D 배열을 2D 배열로 변환 (0) | 2020.09.12 |
| 힙 크기보다 훨씬 많은 메모리를 사용하는 Java (또는 올바른 Docker 메모리 제한 크기) (0) | 2020.09.12 |



