片段继承Android [英] Fragments inheritance Android

查看:153
本文介绍了片段继承Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能/建议让不同的片段在Android中相互继承?

Is it possible/recommanded to let different fragments inherit from each other in Android?

初始化已在超类中初始化的内容的最佳方法是什么并添加东西? ( - >例如像在构造函数中使用super()然后初始化其他对象的普通子类一样)

What would be the best way to initialize things that are already initialized in the superclass and add things to it ? (-> for example like the normal subclasses that use super() in their constructor and then initializing other objects )

我在互联网上看了但是我找不到多少关于此的信息。
我知道可以返回super.onCreateView()但你不能在那之后初始化其他对象/视图....

I looked on the internet but i didn't found much information on this. I know that it's possible to do return super.onCreateView() but you can't initialize other objects/views after that....

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

    super.onCreateView()???


    //initialize other objects here

    //you have to return a view ...
}


推荐答案

是的,是允许的。为什么不?例如,如果您有许多片段,即显示列表,您可以将所有常用方法放在FragmentList中,然后继承其他片段,仅添加唯一方法或覆盖super中的方法(如果需要)。

但是重写 onCreateView()可能会增加布局处理的难度。在我最近的项目中,我在超类中创建了一个方法 inflateFragment(),如下所示:

Yes, it is allowed. Why not? For example, if you have a number of Fragments, that display lists, you could put all common methods in FragmentList, and then inherit other fragments, adding only unique methods or overriding the ones from super if needed.

But overriding onCreateView() could raise difficulties in layouts handling. In my recent project I instead created a method inflateFragment() in the super class as follows:

BaseFragment.java

protected View inflateFragment(int resId, LayoutInflater inflater, ViewGroup container) {
    View view = inflater.inflate(resId, container, false);
    FrameLayout layout = (FrameLayout)view.findViewById(R.id.fragment_layout);
    /*
     *  Inflate shared layouts here
     */
    . . .
    setHasOptionsMenu(true);
    return view;
}

由于结构原因,每个片段布局资源都包含在 FrameLayout id = fragment_layout 。但您可以自由使用LinearLayout或您需要的任何父视图。

Because of the structure, each and every fragment layout resource is wrapped in a FrameLayout with id = fragment_layout. But you're free to use LinearLayout or whatever parent view you need.

然后在继承的片段中:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflateFragment(R.layout.my_fragment, inflater, container);
    /*
     *  Do things related to this fragment
     */
    ...
    return view;
}

这篇关于片段继承Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆