我有一個LinearLayout
含有Views
與背景Drawable
(具有圓角矩形形狀和中風)。他們充當顏色選擇按鈕。最初,第一個按鈕的背景較粗(4px而不是1px)。一切都很好(見下圖左側)。
我想要什麼:
然而,當我按這樣的按鈕,我想從先前選擇按鈕刪除粗的筆劃,並將其應用到實際的按鈕。我嘗試以下方式(只有一個片段):
// get layout
LinearLayout favoriteColorsLayout = (LinearLayout) findViewById(R.id.favoriteColorsLayout);
// get view at old position, update stroke, invalidate
View view = favoriteColorsLayout.getChildAt(selectedColorButton);
GradientDrawable drawable = (GradientDrawable) view.getBackground();
drawable.setStroke(1, Color.parseColor("#bbbbbb"));
view.invalidate(); // do I need this?
// also update stroke of new view
..
// re-layout
favoriteColorsLayout.requestLayout(); // do I need this?
我看到:
事實上較厚的行程移動可惜佈局是錯誤的算帳!按鈕2-4的彩色背景在圍繞它們的筆畫變粗時應變細,以便它們仍然適合包含的佈局,但這種情況不會發生(請參閱下圖的右側)。相反,中風被部分切斷(因爲否則它將被繪製在視圖的邊界之外)。這不是一個理想的效果。
我需要做些什麼才能獲得理想的效果呢? 我知道在運行時只有多少顏色的按鈕,所以我更喜歡一個編程解決方案。
其實我開始認爲它可能是一個Android錯誤,因爲在默認情況下在邊界外繪製筆畫肯定不是期望的行爲。我看到在模擬器和API級別23的效果,以及我的舊手機與API級別11
佈局XML的位。線性佈局(查看以編程方式添加):
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:id="@+id/favoriteColorsLayout"></LinearLayout>
按鈕瀏覽次數:
<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/color_selection_button_size"
android:layout_height="@dimen/color_selection_button_size"
android:layout_margin="@dimen/color_selection_button_margin"
android:layout_gravity="center"
android:background="@drawable/color_selection_cell_background">
</View>
的按鈕背景繪製(color_selection_cell_background.xml):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<stroke
android:width="1px"
android:color="#bbbbbb"/>
<corners
android:radius="5px" />
<gradient
android:angle="90"
android:centerX="0.5"
android:centerY="0.5"
android:startColor="#aaaaaa"
android:endColor="#bbbbbb"
android:type="linear" />
</shape>
您可以發佈佈局XML嗎? –
@JimRhodes當然。被附上。 – Trilarion
作爲評論:我真的想要一個程序化解決方案,因爲我不知道每個按鈕在運行前的數量或漸變顏色。 – Trilarion