Reputation: 2707
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?
Upvotes: 32
Views: 45740
Reputation: 542
an easier way:
public static void setLayoutWeight(View view , float weight)
{
((LinearLayout.LayoutParams) view.getLayoutParams()).weight = weight;
view.requestLayout();
}
Upvotes: 0
Reputation: 22306
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
..
Upvotes: 64
Reputation: 9872
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);
Upvotes: 0
Reputation: 859
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
Upvotes: 18