以编程方式设置LayoutParams

我将一个游戏中的聊天模块放入应用程序中。 我将收到的文本消息添加到LinearLayout视图中。 我想将布局参数设置为TextView,但以下代码崩溃并且错误消息让我感到困惑。

private void addChat(String chat, String when,  Boolean mine) {
    int leftMargin;

    TextView tv = new TextView(this);
    llview.addView(tv);
    tv.setTextColor(Color.WHITE);
    tv.setTextSize(2,25);
    tv.setText(chat);
    if (mine) {
        leftMargin = 5;
        tv.setBackgroundColor(0x7C5B77);
    }
    else {
        leftMargin = 50;
        tv.setBackgroundColor(0x778F6E);
    }
    final ViewGroup.MarginLayoutParams lpt =(MarginLayoutParams)tv.getLayoutParams();
    lpt.setMargins(leftMargin,lpt.topMargin,lpt.rightMargin,lpt.bottomMargin);

    tv.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));

}

当它运行时,所有上述代码都会执行,但它会在android运行时崩溃,如下所示:

03-13 14:15:38.513: E/AndroidRuntime(12985): java.lang.ClassCastException:      android.view.ViewGroup$LayoutParams

并通过调试器逐步完成,它实际上处理所有这些行

但是当尝试渲染具有同样神秘的异常的详细信息时barf:

android.view.ViewGroup$LayoutParams

那么,为了达到这个状态做了什么? 我应该做些什么来交替左/右缩进信息?


只需从底部进行替换并添加此项

tv.setLayoutParams(new ViewGroup.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT));

之前

llview.addView(tv);

创建视图后,我们必须添加布局参数。

像这样改变

TextView tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT));

llview.addView(tv);
tv.setTextColor(Color.WHITE);
tv.setTextSize(2,25);
tv.setText(chat);
if (mine) {
    leftMargin = 5;
    tv.setBackgroundColor(0x7C5B77);
}
else {
    leftMargin = 50;
    tv.setBackgroundColor(0x778F6E);
}
final ViewGroup.MarginLayoutParams lpt =(MarginLayoutParams)tv.getLayoutParams();
lpt.setMargins(leftMargin,lpt.topMargin,lpt.rightMargin,lpt.bottomMargin);

  LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                   /*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
                   /*height*/ ViewGroup.LayoutParams.MATCH_PARENT,
                   /*weight*/ 1.0f
            );
            YOUR_VIEW.setLayoutParams(param);
链接地址: http://www.djcxy.com/p/93275.html

上一篇: setting LayoutParams programmatically

下一篇: Set gravity for LinearLayout programmatically