[英]How can I move a CheckBox in relation to its image background? (Android)
我正在使用以下代碼行為checkBox設置背景圖片:
checkBox.setBackgroundResource(R.drawable.myImage);
但是,復選框會自動定位到背景圖像的左中角。 我希望復選框位於背景圖像的右下角。 我該如何實現? 謝謝!
您可以使用它來對齊頁面右下角的CheckBox
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:src="@drawable/myImage"
android:layout_width="match_parent"
android:layout_height="200dp" />
<CheckBox
android:text="CheckBox"
android:layout_gravity="right|bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/checkBox1" />
</FrameLayout>
如果您的父級布局是相對布局,請使用以下代碼:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
checkbox.setLayoutParams(params);
就是這樣:)
對於LinearLayout
它將為:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.RIGHT | Gravity.BOTTOM;
checkbox.setLayoutParams(params);
更新
實際上,要將其對齊到其自己的空間內,您只需執行checkbox.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
重要的提示
僅當您的CheckBox
寬度和高度不是wrap_content
,您才可以這樣做! 換句話說,它不會在任何地方移動。 因此,您應該不斷指定寬度和高度,例如30dp
,但我不建議您這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.