How to programmatically set weight for Button

2020-06-30 12:03发布

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?

标签: android
4条回答
Animai°情兽
2楼-- · 2020-06-30 12:26

an easier way:

public static void setLayoutWeight(View view , float weight)
{
    ((LinearLayout.LayoutParams) view.getLayoutParams()).weight = weight;
    view.requestLayout();
}
查看更多
对你真心纯属浪费
3楼-- · 2020-06-30 12:34

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

查看更多
老娘就宠你
4楼-- · 2020-06-30 12:39

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);
查看更多
在下西门庆
5楼-- · 2020-06-30 12:44
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..

查看更多
登录 后发表回答