如何使用Java在EditText上添加边框?

时间:2017-02-06 11:28:59

标签: java android xml

我正在尝试使用Java编写代码,而不是使用XML并拖放 这就是我所拥有的

  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);

我的边框XML     

<!-- Background Color -->

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

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

</shape>

我尝试了什么但它没有用

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

1 个答案:

答案 0 :(得分:1)

很简单,你需要在drawable文件夹中创建border.xml:

 <?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>

然后将其设为editext.setbackground(R.drawable.border);