动态调整 Android 的碎片大小

5

我想要改变主活动中正在使用的片段的宽度?但是我无法找到它的LayoutParams以更改其默认宽度:

public class MainActivity extends Activity {

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        int widthFfragment = 300;

        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        widthTot = size.x;
        heightTot = size.y;

        findViewById(R.id.f1).getLayoutParams().width = widthTot-widthFfragment;
    }
}

这是我的片段代码:
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/f1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#330000"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment 1"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Fragment1.java

public class Fragment1 extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        //---Inflate the layout for this fragment---
        return inflater.inflate( R.layout.fragment1, container, false);
    }
}

非常感谢。
2个回答

12

您可以通过使用从Fragment.getView()获取的View的LayoutParams实例来完成。我的示例代码:

private void resizeFragment(Fragment f, int newWidth, int newHeight) {
    if (f != null) {
        View view = f.getView();
        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(newWidth, newHeight);
        view.setLayoutParams(p);
        view.requestLayout();       


    }
}

并可按以下方式使用:

resizeFragment(myFragment, 200, 500);
resizeFragment(otherFragment, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

4

你是对的,Fragment 没有 LayoutParams 是因为它是一个概念上的容器,你需要调整 Fragment 中充气的视图的布局参数,或者容器中附加 Fragment 的布局参数。

public class Fragment1 extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    ViewGroup view = (ViewGroup) inflater.inflate( R.layout.fragment1, container, false);

    // TODO Adjust layout params of inflated view here

    return view;
}

这个例子假设你正在填充一个ViewGroup。希望对你有所帮助。

谢谢,我需要在主活动中进行调整,这可行吗? - bill23
我使用LayoutParams并设置适当的大小来解决它。非常感谢。 - bill23

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接