首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在不使用setBackgroundDrawable方法的情况下以编程方式实现Android按钮或TextView边框

问在不使用setBackgroundDrawable方法的情况下以编程方式实现Android按钮或TextView边框
EN

Stack Overflow用户
提问于 2014-04-20 02:53:32
回答 2查看 34.7K关注 0票数 19

我正在寻找一种方法,可以在不使用setBackgroundResource方法的情况下,以编程方式为文本视图或按钮设置边框。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-20 04:16:33

简单的例子如何实现这一点:

activity_main.xml

代码语言:javascript
复制
<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

代码语言:javascript
复制
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);


    }

}
票数 57
EN

Stack Overflow用户

发布于 2014-04-20 03:10:08

我想这会对你有帮助。

代码语言:javascript
复制
 <?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" />
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23174100

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档