简体   繁体   中英

How do i add a border on EditText with Java?

I am trying to code layout with Java, instead to use XML and drag and drop This is what i have

  RelativeLayout relativeLayout = new RelativeLayout(this);
    EditText username = new EditText(this);
    Button mybutton = new Button(this);

    mybutton.setId(1);
    username.setId(2);

    RelativeLayout.LayoutParams usernameDetails =
            new

                    RelativeLayout.LayoutParams(

                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
            );
    usernameDetails.addRule(RelativeLayout.ABOVE, mybutton.getId());
    usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
    usernameDetails.addRule(RelativeLayout.CENTER_VERTICAL);

    //adding margins between widgets
    usernameDetails.setMargins(0,0,0,50);

My border XML

<!-- Background Color -->

<!-- Border Color -->
<stroke android:width="3dp" android:color="#ffffff" />

<!-- Round Corners -->
<corners android:radius="15dp" />

</shape>

What i have tried and it doesn't work

      username.setBackground(R.drawable.border);
      username.setBackgroundResource(R.drawable.border);

Its simple, you need to create border.xml in drawable folder:

 <?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners
        android:radius="2dp"
        />
    <solid android:color="#ffffff"
        />
    <stroke
        android:width="3dp"
        android:color="#000000" />
</shape>

then set it as editext.setbackground(R.drawable.border);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM