Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - setting LayoutParams programmatically

Tags:

android

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 ?

like image 293
Martin Avatar asked Mar 13 '12 05:03

Martin


People also ask

What is the usage of the command android layout_ gravity?

The android:layout_gravity is used to arrange the position of the entire View relative to it's container.


2 Answers

Just replace from bottom and add this

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

before

llview.addView(tv); 
like image 194
Khan Avatar answered Oct 05 '22 03:10

Khan


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); 
like image 22
RajaReddy PolamReddy Avatar answered Oct 05 '22 02:10

RajaReddy PolamReddy