在android中以编程方式设置片段参数

时间:2012-05-21 10:16:11

标签: android android-fragments compatibility

如何以编程方式设置片段的高度,宽度,边距等参数。我正在添加像

这样的片段
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    MyListFragment myListFragment = new MyListFragment();
    fragmentTransaction.add(1, myListFragment);

    DetailFragment detailFragment = new DetailFragment();
    fragmentTransaction.add(1, detailFragment);

    fragmentTransaction.commit();

我也在使用像android-support-v4.jar这样的compatabilty jar。

感谢。

3 个答案:

答案 0 :(得分:7)

  

如何以编程方式设置碎片的高度,宽度,边距等参数

碎片没有"参数,如高度,宽度,边距和#34;。 ViewViewGroup有"参数,如身高,宽度,边距"。因此,您要么调整放置片段的容器(由于某些奇怪的原因,您在上面的示例中声明为1),或者调整View您的Fragment 1}}从onCreateView()返回。

答案 1 :(得分:0)

CommonsWare的其他信息,您可以调整由onCreateView()返回的View,这让我想到了另一种方法:只需获取Fragments视图,然后调整该视图的LayoutParams。

// use the appropriate LayoutParams type and appropriate size/behavior
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(left, top, right, bottom);
theFragment().getView().setLayoutParams(params);

答案 2 :(得分:0)

我认为这里有一个有效的案例,可以通过程序设计在片段的视图上添加边距,而不是在被充气的容器上添加边距。

例如,要与其他视图共享容器布局。

就我而言,我有一个全屏FrameLayout,它的顶部包含一个按钮,然后整个屏幕由膨胀的片段拍摄。 我可以将两个FrameLayout嵌套在另一个之中,但这对绘制性能不利,更好的选择是将片段直接膨胀到根FrameLayout中,但给其view topMargin以防止其隐藏按钮。

以下是一些代码:

FragmentManager fm = getSupportFragmentManager();
Fragment fragment = new MyFragment();
fm.beginTransaction().add(R.id.container, fragment, "main").commit();

// wait for the fragment to inflate its view within container
container.addOnLayoutChangeListener(new OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (fragment.getView() != null) {
            LayoutParams lp = new LayoutParams(MATCH_PARENT, MATCH_PARENT);
            lp.topMargin = 50; // you need to translate DP to PX here!
            fragment.getView().setLayoutParams(lp);

            container.removeOnLayoutChangeListener(this); // prevent infinite loops
        }
    }
});
相关问题