設定Android中RadioButton的圖檔大小和位置
今天在使用RadioGroup時遇到一個問題,在布局檔案中設定好RadioGroup後結果預覽起來圖檔非常大,這根本不是我想要的效果。下面是解決問題的過程:
布局檔案
<RadioGroup
android:id="@+id/rg_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_vertical"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rbtn_home_news"
style="@style/Style_home_Rbtn"
android:drawableTop="@drawable/selector_home_rbtn_news"
android:text="新聞"
/>
<RadioButton
android:id="@+id/rbtn_home_live"
style="@style/Style_home_Rbtn"
android:drawableTop="@drawable/selector_home_rbtn_live"
android:text="視訊"
/>
<RadioButton
android:id="@+id/rbtn_home_tuijian"
style="@style/Style_home_Rbtn"
android:drawableTop="@drawable/selector_home_rbtn_tuijian"
android:text="推薦"
/>
<RadioButton
android:id="@+id/rbtn_home_me"
style="@style/Style_home_Rbtn"
android:drawableTop="@drawable/selector_home_rbtn_me"
android:text="我"
/>
</RadioGroup>
效果:
這是因為RadioButton繼承自button,當你給RadioButton設定圖檔背景時,圖檔會被拉伸,而導緻得不到我們預期的效果。
而且RadioButton并沒有設定相關屬性來解決這個問題,設定固定寬高是沒有用的。
那麼怎麼解決呢?
查了一下資料,發現一種解決辦法:
在代碼中如下設定即可:
private void initView() {
//定義底部标簽圖檔大小和位置
Drawable drawable_news = getResources().getDrawable(R.drawable.selector_home_rbtn_news);
//當這個圖檔被繪制時,給他綁定一個矩形 ltrb規定這個矩形
drawable_news.setBounds(0, 0, 50, 50);
//設定圖檔在文字的哪個方向
rbtn_News.setCompoundDrawables(null, drawable_news, null, null);
//定義底部标簽圖檔大小和位置
Drawable drawable_live = getResources().getDrawable(R.drawable.selector_home_rbtn_live);
//當這個圖檔被繪制時,給他綁定一個矩形 ltrb規定這個矩形
drawable_live.setBounds(0, 0, 50, 50);
//設定圖檔在文字的哪個方向
rbtn_Live.setCompoundDrawables(null, drawable_live, null, null);
//定義底部标簽圖檔大小和位置
Drawable drawable_tuijian = getResources().getDrawable(R.drawable.selector_home_rbtn_tuijian);
//當這個圖檔被繪制時,給他綁定一個矩形 ltrb規定這個矩形
drawable_tuijian.setBounds(0, 0, 50, 50);
//設定圖檔在文字的哪個方向
rbtn_Tuijian.setCompoundDrawables(null, drawable_tuijian, null, null);
//定義底部标簽圖檔大小和位置
Drawable drawable_me = getResources().getDrawable(R.drawable.selector_home_rbtn_me);
//當這個圖檔被繪制時,給他綁定一個矩形 ltrb規定這個矩形
drawable_me.setBounds(0, 0, 50, 50);
//設定圖檔在文字的哪個方向
rbtn_Me.setCompoundDrawables(null, drawable_me, null, null);
}
這樣就解決了這個問題,效果如下: