基于设备android的不同片段布局

时间:2014-01-21 14:24:02

标签: java android android-layout fragment

我正在开发一个利用片段的android应用程序。我使用了创建向导中生成的片段的标准模板。现在,我想在'mTwoPane'为真时使用不同的'ItemListFragment'布局(屏幕尺寸大于600dp)。单个窗格设备上的布局将具有标题和2x3图标布局,而mTwoPane设备将没有标题并且将具有1x6布局,因此所有图标将在彼此之下。

在我的ItemListActivity.java中,检查或item_detail_container存在。如果是这样,则mTwoPane设置为true。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_item_list);

        if (findViewById(R.id.item_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-large and
            // res/values-sw600dp). If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;

            // In two-pane mode, list items should be given the
            // 'activated' state when touched.
            ((ItemListFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.item_list))
                    .setActivateOnItemClick(true);
        }


    }

我的第一个想法是在我的ItemListFragment中检查mTwoPane,并根据此选择RootView。但我无法让它发挥作用。这是我在ItemListFragment中所做的:

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view;
        boolean mTwoPane;
        if (getView().findViewById(R.id.item_detail_container) != null) {
            mTwoPane = true;
        }
        else mTwoPane = false;

        if(!mTwoPane){
            view = inflater.inflate(R.layout.mobile_list, container, false);
        }
        else{
            view = inflater.inflate(R.layout.tablet_list, container, false);
        }

        return view;
    }

但这显然不起作用,因为视图需要在可以检查或item_detail_container存在之前进行实例化。

然后我开始思考,片段应该知道布局吗?也许我应该有2个列表布局,一个用于平板电脑,一个用于移动设备。但话说回来,

setContentView(R.layout.activity_item_list);

必须首先调用以检查mTwoPane是否为真。

这样做的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

Android将根据资源限定符或存储桶选择要使用的布局资源。

e.g。

布局MDPI 布局华电国际 布局XLARGE 布局端口 布局sw600dp

这些都是资源桶,都可以包含名为activity_item_list的布局文件。然后,Android将根据当前设备属性选择要使用的布局文件。

因此解决方案是创建一个存在于布局文件夹中的list_fragment布局文件,以及layout-sw600dp文件夹(或您当前拥有的任何文件夹)。可以为平板电脑调整layout-sw600dp文件夹中的布局。

阅读这些文章以获取更多信息:

http://android-developers.blogspot.co.uk/2011/07/new-tools-for-managing-screen-sizes.html http://developer.android.com/guide/practices/screens_support.html http://developer.android.com/guide/topics/resources/providing-resources.html

相关问题