2017-02-06 70 views
0

我試圖用Java代碼的佈局,而不是使用XML和拖放 這是我如何在EditText上添加一個邊界與Java?

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