Android Button 或 TextView Border 以编程方式不使用 setBackgroundDrawable 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23174100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android Button or TextView Border programmatically without using setBackgroundDrawable method
提问by Vishanth
I am looking for a way to put a border for either textview or a button programmatically without using the setBackgroundResource method.
我正在寻找一种在不使用 setBackgroundResource 方法的情况下以编程方式为 textview 或按钮放置边框的方法。
The goal I am trying to achieve here is, to change the background color dynamically but with a fixed border. When I use the setBackgroundResource method for the background border, the border doesn't remain after changing the background color programmatically.
我在这里尝试实现的目标是动态更改背景颜色但具有固定边框。当我对背景边框使用 setBackgroundResource 方法时,以编程方式更改背景颜色后边框不会保留。
回答by janzoner
Simple example how could be this achieved:
简单的例子是如何实现的:
activity_main.xml
活动_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>
MainActivity.java
主活动.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);
}
}
回答by Vishanth
I thing this will help you.
我想这会帮助你。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#FFFFFF"
android:endColor="#FFFFFF"
android:angle="270" />
<corners android:radius="3dp" />
<stroke android:width="5px" android:color="#eecc68" />
</shape>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginLeft="52dp"
android:layout_marginTop="39dp"
android:background="@drawable/button"
android:text="Button" />