Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...