Change shape border color at runtime

旧巷老猫 提交于 2019-12-20 16:28:09

问题


I have this shape in my drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp" />
    <solid android:color="#ffffff" />
    <stroke android:width="2dp" android:color="#B5B5B5"/>
</shape>

This define a rectangle with rounded corners and I can apply it as background to any panel like this: android:background="@drawable/round_corner_shape".

Here comes the question: I have few panels on my application, with the same shape as background, but for each shape I want a different border (stroke) color. I don't want to create 3 shapes, the only difference to be on the stroke color. Is it possible to change at runtime the stroke value?


回答1:


I had the same problem. In my case, I had a GridView, which the items in grid could have the border color changed by the user at runtime.

So, in the gridviewAdapter for that grid, I did the following in the getView method (the one that generates the view for the adapter)

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    convertView = inflater.inflate(R.layout.griditem, null);
    GradientDrawable gradientDrawable = (GradientDrawable) convertView.getBackground(); 

    gradientDrawable.setStroke(2, mColor); 
    convertView.invalidate();
    return convertView;
}

mColor is a int that represents the color, much like we do in the xml files. In java code, instead of "#" we use "0x" to define it in the AARRGGBB format. For example, use 0xFF000000 for 100% opaque BLACK and 0xFF0000FF for 100% opaque BLUE. Explaining this here since the google api 'helpfully' tells that the int color is "the color of the stroke".

This solved my problem... I guess you can try something similar for your case.




回答2:


Hi you can try create your background on runtime, then you can change it whenever you want.

RoundRectShape rect = new RoundRectShape(
  new float[] {30,30, 30,30, 30,30, 30,30},
  null,
  null);
ShapeDrawable bg = new ShapeDrawable(rect);
bg.getPaint().setColor(0x99FFFFFF);
view.setBackgroundDrawable(bg);


来源:https://stackoverflow.com/questions/13585496/change-shape-border-color-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!