Android添加边框以编程方式编辑文本

Lun*_*box 12 android background-color android-edittext

我使用这个例子并试图以编程方式将它添加到我的编辑文本中editText.setBackgroundResource(R.drawable.edit_text_back);,但它不起作用.我怎么能做到这一点?有什么建议或想法吗?

编辑 editText也是以编程方式定义的.

EditText editText = new EditText(this.getApplicationContext());
Run Code Online (Sandbox Code Playgroud)

我把它添加到表格行

受审

editText.setBackground(getResources().getDrawable(R.drawable.edit_text_back));
editText.setBackgroundDrawable(getResources().getDrawable(R.drawable.edit_text_back));
Run Code Online (Sandbox Code Playgroud)

编辑文本创建

TableRow row = (TableRow) findViewById(R.id.table_row_kind);
TableRow.LayoutParams rowP = new TableRow.LayoutParams();
        rowP.setMargins(10, 0, 0, 0);
editText = new EditText(this.getApplicationContext());
editText .setGravity(Gravity.FILL_HORIZONTAL);
editText .setLayoutParams(rowP);
editText .setFilters(new InputFilter[]{txtFilter});
editText.setBackground(getResources().getDrawable(R.drawable.edit_text_back));
Run Code Online (Sandbox Code Playgroud)

row.xml

<TableRow
    android:id="@+id/table_row_kind"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="5dip" >

    <TextView
       android:layout_width="250sp"
       android:text="Kind"
       android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
Run Code Online (Sandbox Code Playgroud)

小智 17

那么我也有同样的问题,我通过以下方式解决.它是一个xml文件,将它放在你的drawable文件夹中,并将这个xml设置为EditText的背景

活动代码:

EditText foo = (EditText)findViewById(R.id.editText);
foo.setBackgroundResource(R.drawable.backtext);
Run Code Online (Sandbox Code Playgroud)

backtext.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
       <solid android:color="#ffffff" />
       <stroke android:width="1dip" android:color="#000000"/>
    </shape>
Run Code Online (Sandbox Code Playgroud)


Pan*_*ora 10

将edittext.xml文件创建为drawable文件夹

<?xml version="1.0" encoding="utf-8"?>
<!--  res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#FFFFFF"/>
<stroke
    android:width="1dp"
    android:color="@android:color/black" />
<corners
 android:bottomRightRadius="15dp"
 android:bottomLeftRadius="15dp"
 android:topLeftRadius="15dp"
android:topRightRadius="15dp"/>
</shape>


in your main.xml
<EditText
background="drawable/edittext.xml"
/>
Run Code Online (Sandbox Code Playgroud)