在android中动态设置片段视图的宽度

时间:2016-04-07 07:22:31

标签: android

以下是代码:

 View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);

如何将此布局的宽度设置为屏幕的一半?

2 个答案:

答案 0 :(得分:0)

而不是使你的片段视图成为屏幕的50%。设置容器视图的宽度,将Fragment放在屏幕的50%处。

答案 1 :(得分:0)

首先你得到屏幕的宽度:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
try {
    display.getRealSize(size); 
} catch (NoSuchMethodError err) { // Due to some sdk compatibility issue
    display.getSize(size);
}
int width = size.x; // this is your screen width 

现在,将其设置为布局:

View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
LinearLayout.LayoutParams layout_lp = new LinearLayout.LayoutParams(
                            (int)(width/2), LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(layout_lp);