Android Button 或 TextView Border 以编程方式不使用 setBackgroundDrawable 方法 [英] Android Button or TextView Border programmatically without using setBackgroundDrawable method

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

问题描述

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

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.

推荐答案

如何实现的简单示例:

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


    }

}

这篇关于Android Button 或 TextView Border 以编程方式不使用 setBackgroundDrawable 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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