Android Button or TextView Border programmatically without using setBackgroundDrawable method

StackOverflow https://stackoverflow.com/questions/23174100

문제

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

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


    }

}

다른 팁

I think 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" />
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top