Android Button or TextView Border programmatically without using setBackgroundDrawable method

后端 未结 2 478
感动是毒
感动是毒 2020-12-14 18:15

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 achie

相关标签:
2条回答
  • 2020-12-14 18:42

    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);
    
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-14 18:54

    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" />
    
    0 讨论(0)
提交回复
热议问题