naresh
naresh

Reputation: 10392

android - How to fix the position of view in Linear Layout programmatically

I am adding the LinearLayout(child view) to another LinearLayout(parentview) programatically here I want to set the position of child view to center_horizontal. How to do that? please can somebody help me.

code

LinearLayout linearLayoutstate = new LinearLayout(this);

linearLayoutstate.setOrientation(LinearLayout.HORIZONTAL);

TextView stateTitletv = new TextView(this);

stateTitletv.setText("tv1");

TextView state_valuetv = new TextView(this);    

state_valuetv.setText("tv2");    

linearLayoutstate.addView(stateTitletv);

linearLayoutstate.addView(state_valuetv);

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT,Gravity.CENTER_HORIZONTAL);

LL_SelectedFilters.addView(linearLayoutstate,layoutParams);

Upvotes: 2

Views: 6489

Answers (2)

Sébastien
Sébastien

Reputation: 14821

The key to your problem resides in the gravity field of the LinearLayout.LayoutParams of your child view:

LinearLayout.LayoutParams lllp=(LinearLayout.LayoutParams)linearLayoutstate.getLayoutParams();

lllp.gravity=Gravity.CENTER_HORIZONTAL;
linearLayoutstate.setLayoutParams(lllp);

LL_SelectedFilters.addView(linearLayoutstate);

Upvotes: 0

Shankar Agarwal
Shankar Agarwal

Reputation: 34765

Use this a minor change:::

  LinearLayout linearLayoutstate = new LinearLayout(this);

  linearLayoutstate.setOrientation(LinearLayout.HORIZONTAL);
  linearLayoutstate.setGravity(Gravity.CENTER_HORIZONTAL);
  LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);

  TextView stateTitletv = new TextView(this);

  stateTitletv.setText("tv1");

  TextView state_valuetv = new TextView(this);

  state_valuetv.setText("tv2");

  linearLayoutstate.addView(stateTitletv);

  linearLayoutstate.addView(state_valuetv);

  LL_SelectedFilters.addView(linearLayoutstate,layoutParams);

Upvotes: 1

Related Questions