Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

android - setting LayoutParams programmatically

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

}

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just replace from bottom and add this

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

before

llview.addView(tv);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...