Android的按钮或TextView的边境编程,而无需使用setBackgroundDrawable方法 [英] Android Button or TextView Border programmatically without using setBackgroundDrawable method

查看:407
本文介绍了Android的按钮或TextView的边境编程,而无需使用setBackgroundDrawable方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一种方式来把边境TextView的两种或按钮编程,而无需使用setBackgroundResource方法。

I am looking for a way to put a border for either textview or a button programmatically without using the setBackgroundResource method.

我想在这里实现的目标是,要动态地但有一个固定的边界改变背景颜色。
当我使用setBackgroundResource方法为背景的边界,边界不留编程方式更改背景颜色后。

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.

推荐答案

简单的例子可以如何实现这样:

Simple example how could be this achieved:

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>

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.setBackgroundDrawable(gd);


    }

}

这篇关于Android的按钮或TextView的边境编程,而无需使用setBackgroundDrawable方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆