代碼

2011-11-29 26 views
1

定義選擇,我有以下選擇:代碼

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item> 
     <shape android:shape="rectangle"> 
      <solid android:color="#00000" /> 
      <corners android:radius="10dp" /> 
      <stroke android:width="5px" android:color="#FFFFFF" /> 
     </shape> 
    </item> 

</selector> 

,我想在代碼中定義。我設法儘量來,因爲這:

StateListDrawable states = new StateListDrawable(); 

float[] roundedCorner = new float[] { 10, 10, 10, 10, 10, 10, 10, 10 }; 
float[] innerRoundedCorner = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 }; 
RectF inset = new RectF(5, 5, 5, 5); 
RoundRectShape round = new RoundRectShape(roundedCorner, inset, innerRoundedCorner);   

ShapeDrawable shape = new ShapeDrawable(round);  
shape.getPaint().setColor(Color.WHITE); 

states.addState(new int[] {}, shape); 

button.setBackgroundDrawable(states); 

這給了我一個白邊的按鈕,但我無法設置按鈕的背景顏色。 這是如何在代碼中實現的?

+0

你爲什麼不使用標準的Android狀態代碼從'機器人.R.attr.state_XXX'? – teoREtik

+0

而且它是否正確設置'shape'對象而不是'狀態'對象爲BackgroundDrawable? – teoREtik

+0

@teoREtik android.R.attr.state只定義您設置Drawable的狀態,我希望能夠根據某些條件更改代碼中的顏色。所以我需要一種方法來繪製代碼。 – Drejc

回答

0

試試這個代碼

StateListDrawable states = new StateListDrawable(); 

    float[] roundedCorner = new float[] { 10, 10, 10, 10, 10, 10, 10, 10 }; 
    float[] innerRoundedCorner = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 }; 
    RectF inset = new RectF(0, 0, 0, 0); 

    RoundRectShape round = new RoundRectShape(roundedCorner, inset, innerRoundedCorner);   
    LinearGradient lg = new LinearGradient(0, 0, 100, 100, Color.BLUE, Color.CYAN, TileMode.REPEAT); 

    ShapeDrawable shape = new ShapeDrawable(round); 
    shape.getPaint().setStyle(Style.FILL_AND_STROKE); 
    //shape.getPaint().setColor(Color.WHITE); 
    shape.getPaint().setShader(lg); 

    states.addState(new int[] {}, shape); 

    button.setBackgroundDrawable(shape); 

你定義它是添加在RoundRectShape的RectF的插圖對象傳遞0值你得到了完整的RoundRectShape

檢查this

+0

以下代碼不會在形狀周圍產生邊緣。我希望邊緣與內部顏色不同。 – Drejc

2

RoundRectShape可以在RectF上接受null,那麼你將有一個填充形狀。 此外,當您使用的狀態,您可以在選擇指定屬性:state_pressed,state_single等

試試這個代碼:

private static StateListDrawable getStateListDrawable(int color, Context context) { 
    StateListDrawable stateListDrawable = new StateListDrawable(); 

    float[] roundedCorner = new float[]{4, 4, 4, 4, 4, 4, 4, 4}; 
    float[] innerRoundedCorner = new float[]{0, 0, 0, 0, 0, 0, 0, 0}; 
    RoundRectShape roundedShape = new RoundRectShape(roundedCorner, null, innerRoundedCorner); 

    ShapeDrawable pressedDrawable = new ShapeDrawable(roundedShape); 
    pressedDrawable.getPaint().setColor(context.getResources().getColor(R.color.default_bg)); 
    stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, pressedDrawable); 

    ShapeDrawable normalDrawable = new ShapeDrawable(roundedShape); 
    normalDrawable.getPaint().setColor(context.getResources().getColor(color)); 
    stateListDrawable.addState(new int[]{}, normalDrawable); 

    return stateListDrawable; 
}