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 ?
The android:layout_gravity is used to arrange the position of the entire View relative to it's container.
Just replace from bottom and add this
tv.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
before
llview.addView(tv);
after creating the view we have to add layout parameters .
change like this
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With