2017-07-24 29 views
1

如何以編程方式更改<solid android:color= />如何通過編程更改形狀純色?

我定義的自定義形狀元素: my_item.xml:

<shape android:shape="oval"> 
    <solid android:color="#FFFF0000"/> 
</shape> 

和重用它在另一個佈局: grid_view.xml:

<LinearLayout> 
    <ImageView ... android:src="@drawable/my_item android:id="@+id/myitemid" /> 
</LinearLayout> 

下不起作用:

public class ShapeItemAdapter extends BaseAdapter { 

    @Override 
    public View getView(int i, View view, ViewGroup viewGroup) { 
      view = inflter.inflate(R.layout.grid_view, null); 
      ImageView shape = (ImageView) view.findViewById(R.id.myitemid); 
      shape.setBackgroundColor(0xBCCACA); //does not work 
    } 
} 
+0

你問過之前是否檢查過[this](https://stackoverflow.com/questions/17823451/set-android-shape-color-programmatically)? – Piyush

+0

可能重複的https://stackoverflow.com/questions/17823451/set-android-shape-color-programmatically –

+0

可能重複[以編程方式設置android形狀顏色](https://stackoverflow.com/questions/17823451/set -android-shape-color-programmatically) –

回答

0

試試這個

ImageView shape = (ImageView) view.findViewById(R.id.myitemid); 
GradientDrawable bgShape = (GradientDrawable)shape.getBackground(); 
bgShape.setColor(Color.BLACK); 
+0

形狀是一個'ShapeDrawable' ... – membersound

0

獲取ShapeDrawable並設置顏色:

ImageView shape = (ImageView) view.findViewById(R.id.myitemid); 
ShapeDrawable shapeDrawable = (ShapeDrawable) shape.getBackground(); 
shapeDrawable.getPaint().setColor(ContextCompat.getColor(context,R.color.my_color)); 

您可以等到佈局已經繪就:

ViewTreeObserver to = shape.getViewTreeObserver(); 
to.addOnGlobalLayoutListener (new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
     layout.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
     ImageView shape = (ImageView) view.findViewById(R.id.myitemid); 
     ShapeDrawable shapeDrawable = (ShapeDrawable) shape.getBackground(); 
     shapeDrawable.getPaint().setColor(ContextCompat.getColor(context,R.color.my_color)); 
    } 
}); 
+0

'shape.getBackground()'返回'null'。爲什麼我沒有背景? – membersound

+0

我更新了我的回答@membersound – Fori

0

試試這個: -

從資源和變革讓您繪製形狀顏色。然後您可以設置爲圖像視圖的背景。

 GradientDrawable drawable = (GradientDrawable) mContext.getResources() 
      .getDrawable(R.drawable.todo_list_circle); 
    drawable.mutate(); 
    drawable.setColor(mColor); 
0

我發現這裏提供的答案沒有一個是正確的。重要的是:在形狀上使用getDrawable(),而不是getBackground()

GradientDrawable shape = (GradientDrawable) icon.getDrawable(); 
shape.setColor(Color.BLACK); 
相關問題