android - 以编程方式设置形状颜色

标签 android android-layout

我正在使用键盘 View ,其中我有自定义的 xml 形状,我可以设置特定的按钮颜色是我的 shape xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <solid android:color="#80B3B3B3"/> 
  <corners android:bottomRightRadius="2dp" android:bottomLeftRadius="2dp" 
     android:topLeftRadius="2dp" android:topRightRadius="2dp"/> 
</shape>

然后我为 Keyboard View 覆盖我的 onDraw 方法:

@Override
    public void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        List<Key> keys = getKeyboard().getKeys();
        for (Key key : keys) {            
            Drawable dr = (Drawable)this.getResources().getDrawable(R.drawable.keyshape);               
            dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
            dr.draw(canvas);
        }
    }

现在我想允许该用户设置形状的这种颜色,知道如何在绘制之前设置它吗?

最佳答案

首先,您应该做一个您想要设置和扩展的自定义 View (TextView 或 Button w/e 我将编写示例作为扩展 View )因为您无法以编程方式编辑形状 xml,您将创建它作为一个整体。

覆盖 View 所需的行为和构造函数。现在您将创建一个方法 setGradientColors,它将两种颜色作为 int 值(底部和顶部渐变颜色)。您也可以修改它以设置圆角的半径。

public class GradientView extends View{

    public GradientView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public GradientView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // TODO Auto-generated constructor stub
    }
    public GradientView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public void setGradientColors(int bottomColor, int topColor) {
        GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] {bottomColor, topColor});
        gradient.setShape(GradientDrawable.RECTANGLE);
        gradient.setCornerRadius(10.f);
        this.setBackgroundDrawable(gradient);
    }

}

您将使用这个新 View 并以编程方式将形状设置为:

GradientView view = (GradientView) findViewById(R.id.customView);
// bottom color - top color order
view.setGradientColors(Color.parseColor("#ff0000"), Color.parseColor("#0000ff"));

如果您需要进一步的帮助和有关基础知识的完整解释,我已经在我的项目中通过遵循此 Link 实现了这一点

希望它也能帮到你。

关于android - 以编程方式设置形状颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23126064/

相关文章:

javascript - PhoneGap GPS 检测插件不起作用

android - 将 RelativeLayout 分成两半

java - 无法引用以不同方法定义的内部类中的非最终变量-请帮助我,我是新手

android - 在代码中创建新参数不起作用?

Android - 让进度条平稳增加,而不是跳得更大。

android - 将 TextView 对齐到 RelativeLayout 的中心

Android - 在屏幕顶部显示可关闭的对话框(就像在 Chrome 中一样)

Android ConstraintLayout - 如何将 View 移动到占用的空间?

android - Android 上的 Tensorflow lite,如何定义 'runForMultipleInputsOutputs' 函数的输入和输出?

android - Google Maps V2 android 获取标记图标