以编程方式创建自定义TextView

时间:2014-07-30 17:04:42

标签: android textview

我正在写一个聊天应用。我在代码中为每个聊天创建了文本视图。这包括" addChat"方法和粘贴在下面的chatshape.xml。除了角落在文本框上没有圆角外,一切都很完美。 tv.setBackgroundResource(R.drawable.chatshape)无效。

private void addChat(String chat, String when,  Boolean mine) 
{
    int leftMargin;
    TextView tv = new TextView(this);
    tv.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.MATCH_PARENT)); 

    tv.setTextSize(2,20);
    tv.setPadding(10, 4, 10, 4);
    tv.setBackgroundResource(R.drawable.chatshape);
    tv.setText(chat);
    if (mine) {
        leftMargin = 10;
        tv.setBackgroundResource(R.color.white);
        tv.setTextColor(Color.BLUE);
    }
    else {
        leftMargin = 25;
        tv.setBackgroundResource(R.color.gray);
        tv.setTextColor(Color.WHITE);
    }
    this.messageScroll.addView(tv);
    final ViewGroup.MarginLayoutParams lpt = (ViewGroup.MarginLayoutParams) tv.getLayoutParams();

    lpt.setMargins(leftMargin,4,10,4);

}

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

  <corners
         android:bottomRightRadius="20px" 
         android:bottomLeftRadius="20px" 
         android:topLeftRadius="20px" 
         android:topRightRadius="20px"/>
</shape>

1 个答案:

答案 0 :(得分:1)

<corners android:radius="8dp" />

<solid android:color="#FFFFFF" />

<stroke
    android:width="1dp"
    android:color="#848482" />

  <padding
    android:bottom="3dp"
    android:left="3dp"
    android:right="3dp"
    android:top="3dp" />  

它有效......!