【问题标题】:Can a fragment extend a fragment activity? [Android]片段可以扩展片段活动吗? [安卓]
【发布时间】:2013-07-01 22:26:03
【问题描述】:

我创建了一个 MainActivity,它包含 3 个可滚动的选项卡(通过使用 ViewPager)。现在这 3 个选项卡中的每一个都是一个片段。另外,我正在使用 ActionBarSherlock (ABS)。

对于第一个片段,我创建了以下类:

public class Fragment_1 extends SherlockFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = inflater.inflate(R.layout.fragment1, container, false);
        return v;
        /* R.layout.fragment1 only contains a TextView. */
    }
}

对于第二个 Fragment,我想扩展一个 FragmentActivity,如下所示。

public class Fragment_2 extends FragmentActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.fragment2);
        }
}

第三个片段与第一个片段相同。

但是当我启动应用程序时,它崩溃了。那么,我在为 Fragment_2 类扩展 FragmentActivity 时错了吗?将 FragmentActivity 甚至 Activity 扩展到片段类是否违法?如果不是,这里有什么问题?

谢谢。


编辑:在@CommonsWare 的回答之后,我更新了我的课程如下:

public class Fragment_2 extends SherlockFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Button send = (Button) findViewById(R.id.bSend); //Error at this line
            //some error free code
            FragmentTransaction t = getSupportFragmentManager().beginTransaction(); //Error at this line
        }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View v = inflater.inflate(R.layout.fragment2, container, false);
    return v;
}

我的最后两个问题是:

  1. 我应该如何访问 Fragment_2 类中的 R.id.bSend 按钮。
  2. Eclipse 建议将 getSupportFragmentManager() 更改为 getFragmentManager()。这样改好吗?

谢谢!

【问题讨论】:

    标签: android android-fragments android-activity android-fragmentactivity


    【解决方案1】:

    将 FragmentActivity 甚至 Activity 扩展为片段类是否违法?

    Fragment 是一个 Java 类。您的片段实现(用作ViewPager 中的页面)必须直接或间接从Fragment 继承。

    Activity 不继承自 FragmentFragmentActivity 不继承自 Fragment。因此,您不能从ActivityFragmentActivity 继承,并且以某种方式Fragment 继承。

    【讨论】:

    • @BornAgain:您可以让Fragment_2 继承自Fragment。请注意,您从未解释过为什么“要扩展 FragmentActivity”。
    • 问题是在Fragment_2 类中,我需要使用setContentView(),为此我需要扩展Activity 或FragmentActivity。但这是不可能的。
    • @BornAgain:“我需要使用 setContentView()”——不,你不需要,因为 Fragment 无法做到这一点。使用 onCreateView() 中的 inflate(),就像在 Fragment_1 中所做的那样。
    • 非常感谢。那解决了它。但现在我又面临两个问题。如果您查看我更新的问题,我会非常有帮助。
    • @BornAgain:删除您的 onCreate() 方法。将Button 逻辑移动到onCreateView(),在inflate() 之后,通过在v 上调用findViewById() 以在膨胀的View 中找到Button。而且我不知道您为什么要在片段中弄乱FragmentTransaction
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 2014-01-01
    相关资源
    最近更新 更多