設置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);
}
這樣就解決了這個問題,效果如下: