Android的 - 设置的LayoutParams编程 [英] android - setting LayoutParams programmatically

查看:121
本文介绍了Android的 - 设置的LayoutParams编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我把一个游戏中的聊天模块到一个应用程序。因为他们接收到一个LinearLayout中观点我加入短信。我想设置布局PARAMS到TextView的,但下面code崩溃和错误消息迷惑我。

I putting an in-game chat module into an app. I am adding text messages as they are received into a LinearLayout view. I want to set the layout params to the TextView but the following code is crashing and the error messages befuddle me.

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

}

在运行时,所有上述code执行时,但它崩溃在Android运行为:     03-13 14:15:38.513:E / AndroidRuntime(12985):java.lang.ClassCastException:android.view.ViewGroup $的LayoutParams

when it runs, all of the above code executes but it crashes in android runtime as: 03-13 14:15:38.513: E/AndroidRuntime(12985): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams

和与调试器步进通过,它实际上处理所有这些行 但随后试图呈现一个同样神秘的异常详细消息时barfs: android.view.ViewGroup $的LayoutParams

and stepping through with the debugger, it actually processes all of these lines but then barfs when trying to render with an equally cryptic exception detailed message: android.view.ViewGroup$LayoutParams

那么,是什么都做去这个国家?我应该怎么做才能有交替的左/右缩进的消息?

So, what have done to get to this state? What should I be doing to have alternating left/right indented messages ?

谢谢, 马丁

推荐答案

刚刚从底部更换和添加​​此

Just replace from bottom and add this

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

llview.addView(tv);

这篇关于Android的 - 设置的LayoutParams编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆