不使用setBackgroundDrawable方法以编程方式安装Android Button或TextView Border

Vis*_*nth 18 android border button textview

我正在寻找一种方法,以编程方式为textview或按钮设置边框,而不使用setBackgroundResource方法.

我试图在这里实现的目标是,动态地改变背景颜色,但具有固定的边框.当我使用setBackgroundResource方法作为背景边框时,在以编程方式更改背景颜色后,边框不会保留.

jan*_*ner 52

简单的例子如何实现:

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="@string/hello_world" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

MainActivity.java

package com.exmple.test;

import android.app.Activity;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GradientDrawable gd = new GradientDrawable();
        gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
        gd.setCornerRadius(5);
        gd.setStroke(1, 0xFF000000);
        TextView tv = (TextView)findViewById(R.id.textView1);
        tv.setBackground(gd);


    }

}
Run Code Online (Sandbox Code Playgroud)