【发布时间】:2021-01-26 11:04:48
【问题描述】:
我尝试过使用以下解决方案,但没有成功
https://stackoverflow.com/questions/32163918/programmatically-change-color-of-shape-in-layer-list
这是我的代码...
Rolling.java
package com.example.app1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
public class Rolling extends AppCompatActivity {
private LayerDrawable layerDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rolling);
LayerDrawable shape = (LayerDrawable) ContextCompat.getDrawable(Rolling.this,R.drawable.dice1);
/* GradientDrawable outer = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.drawable.dice1);
outer.setColor(Color.BLACK);*/
shape.setTint(Color.BLUE);
}
}
activity_rolling.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Rolling">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="44dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/dice1" />
</androidx.constraintlayout.widget.ConstraintLayout>
dice1.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingRight="50dp" android:paddingLeft="50dp">
<!-- Larger blue circle -->
<item
android:id="@+id/dice1"
android:bottom="214dp"
android:top="214dp"
android:left="100dp"
android:right="100dp"
android:gravity="center"
android:tileMode="repeat"
>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape">
<stroke android:width="2dp" android:color="#ff207d94" />
<padding android:left="2dp"
android:top="2dp"
android:right="2dp"
android:bottom="2dp" />
<size android:width="100dp" android:height="100dp"/>
<corners android:radius="5dp" />
<solid android:color="#ffffffff" />
</shape>
</item>
</layer-list>
所以我想以编程方式更改方形的颜色那么我该如何实现呢?
【问题讨论】:
-
你可以使用 ColorFilter。
标签: android android-layout layer-list