32

I need to implement Dialog for my Android app through Java code, so I can't use XML.

I have root LinearLayout where I implement range seek bar, then I have another LinearLayout under root layout, with horizontal orientation, where I want to add two buttons in same row. So I need to set weight to 1, and width to FILL_PARENT and height to WRAP_CONTENT.

How I can do that with Java code?

Bugs Happen
  • 2,169
  • 4
  • 33
  • 59
Zookey
  • 2,637
  • 13
  • 46
  • 80

4 Answers4

64
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
p.weight = 1;

rangeSeekBar.setLayoutParams(p);

I'm not sure which view you want to set the layout params on. I just assumed the rangeSeekbar to show an example. Change if you need.

When using the layout params always use the root's param type..

Ex. if you have a View you want to apply params to within a RelativeLayout use RelativeLayout.LayoutParams..

dymmeh
  • 22,247
  • 5
  • 53
  • 60
18

You can pass it in as part of the LinearLayout.LayoutParams constructor: Did you mean wrap_content?

LayoutParams param = new LinearLayout.LayoutParams(
                         LayoutParams.MATCH_PARENT,
                         LayoutParams.WRAP_CONTENT, 1.0f);

1.0f is the weight

fangmobile
  • 839
  • 8
  • 23
0

Is not using XML a requirement? If not, you could always build your layout in XML and then use a LayoutInflater at run-time to build up your view hierarchy and pass that to setView() on your dialog.

For example:

LayoutInflater inflater = LayoutInflater.from(getActivity());
View v = inflater.inflate(R.layout.my_dialog_layout, null);

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v);
Scott W
  • 9,742
  • 2
  • 38
  • 53
0

an easier way:

public static void setLayoutWeight(View view , float weight)
{
    ((LinearLayout.LayoutParams) view.getLayoutParams()).weight = weight;
    view.requestLayout();
}
Amine Messabhia
  • 357
  • 3
  • 14