为textview设置填充不起作用

时间:2013-08-20 05:23:17

标签: android textview padding

我正在尝试通过textview实现标记。我输入EditText的内容,然后按一个按钮添加标签。 我是以编程方式在文本视图中添加填充和矩形背景,但填充设置没有任何效果。如何添加填充以使其有效?

public void tag_it_callback (View view) {
    Log.v("actv", "tag it callback");
    LinearLayout main_layout = (LinearLayout) findViewById(R.id.main_layout);

    TextView tv = new TextView(this);

    tv.setText( ((EditText) findViewById(R.id.textfield)).getText() );
    main_layout.addView(tv);

    transform_tag(tv);
}

public void transform_tag(TextView tv) {

    // set padding and background
    int padding = 10;
    tv.setPaddingRelative(20, 20, 20, 20);
    tv.setPadding(20, 20, 20, 20);
    tv.setBackgroundResource(R.drawable.border);

    // set layout width and height
    LayoutParams params= (LayoutParams) tv.getLayoutParams();
    Log.v("actv", "params "+params);
    if ( params != null ) {
        params.width=LayoutParams.WRAP_CONTENT;
        params.height=LayoutParams.WRAP_CONTENT;
    } else {
        params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    }
    tv.setLayoutParams(params)
}

border.xml就像这样

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
      <item> 
         <shape android:shape="rectangle">
      <solid android:color="#FF0000" /> 
      <corners
        android:bottomLeftRadius="8dp"
        android:bottomRightRadius="8dp"
        android:topLeftRadius="8dp"
        android:topRightRadius="8dp" />
    </shape>
  </item>   
  <item android:left="5dp" android:right="5dp" android:top="5dp" android:bottom="5dp">  
    <shape android:shape="rectangle"> 
      <solid android:color="#000000" />
    </shape>
   </item>    
     </layer-list>"`<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
      <item> 
    <shape android:shape="rectangle">
      <solid android:color="#FF0000" /> 
      <corners
        android:bottomLeftRadius="8dp"
        android:bottomRightRadius="8dp"
        android:topLeftRadius="8dp"
        android:topRightRadius="8dp" />
    </shape>
  </item>   
  <item android:left="5dp" android:right="5dp" android:top="5dp" android:bottom="5dp">  
    <shape android:shape="rectangle"> 
      <solid android:color="#000000" />
    </shape>
   </item>    
     </layer-list>`

2 个答案:

答案 0 :(得分:63)

我终于找到了问题 我必须在设置填充之前先设置背景。 设置填充然后设置背景不起作用

// does not work
tv.setPadding(20, 20, 20, 20);
tv.setBackgroundResource(R.drawable.border);


// works
tv.setBackgroundResource(R.drawable.border);
tv.setPadding(20, 20, 20, 20);

答案 1 :(得分:0)

tv.setPadding(20, 20, 20, 20);
tv.setBackgroundResource(R.drawable.border);