【问题标题】:How to change the solid color programmatically of a shape in Android?如何在Android中以编程方式更改形状的纯色?
【发布时间】:2016-07-21 13:32:15
【问题描述】:

我正在尝试更改我的Fragmentshapesolid 颜色。

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/icon_circle_background">
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            ...>
            <solid android:color="@color/md_cyan_400"/>
        </shape>
    </item>
    <item
        ...
    </item>
</layer-list>

我似乎无法从我的代码中访问它,并且我已经尝试了以下有关堆栈溢出的答案:

Set android shape color programmatically

How to change shape color dynamically?

Change shape solid color at runtime inside Drawable xml used as background

这些都不起作用或已经过时了。

我尝试更改颜色的片段:

public class GameFragment extends Fragment {
    private Theme currentTheme;
    private Circle currentCircle;
    private int currentOrganisationId;
    private List<Card> circleCards;
    private List<ImageButton> circleButtons;
    private int viewHeight;
    private int viewWidth;
    private int marginCard;
    private int[] tableStarts;
    private RelativeLayout background;
    private ViewTreeObserver vto;

    public GameFragment() {
        circleCards = new ArrayList<>();
        circleButtons = new ArrayList<>();
        tableStarts = new int[9];
    }

    //...

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_game, container, false);
        ...
        background = setBackground(rootView);
        circleCards = currentCircle.getCards();

        return rootView;
    }

    //...

    private void drawCards() {
        circleButtons = new ArrayList<>();
        for (Card card : circleCards) {
            ImageButton myImageButton = new ImageButton(this.getContext()); //generate ImageButton
            myImageButton.setId(card.getCardId()); //Set Id of button
            myImageButton.setBackgroundResource(R.drawable.circle_card_icon);

            //set random color to shape
            ...
        }
    }
}

【问题讨论】:

标签: android shape android-imagebutton


【解决方案1】:

使用这个:

GradientDrawable bgShape = (GradientDrawable)view.getBackground().getCurrent();
bgShape.setColor(Color.BLACK);

.getCurrent 给出选定的可绘制图层列表

使用它不会抛出 java.lang.ClassCastException: android.graphics.drawable.GradientDrawable cannot be cast to android.graphics.drawable.ShapeDrawable 异常。

它非常适合我。

【讨论】:

    【解决方案2】:
    View v = findViewById(R.id.layout_id);
    LayerDrawable shape= (LayerDrawable)v.getBackground();
    shape.setColor(Color.Black);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 2013-07-23
      相关资源
      最近更新 更多