Can a fragment extend a fragment activity? [Android]

▼魔方 西西 提交于 2019-12-08 08:30:24

问题


I have created a MainActivity which consists of 3 tabs which are scrollable (by using ViewPager). Now each of these 3 tabs is a Fragment. Also, I am using ActionBarSherlock (ABS).

For the 1st Fragment, I have created the following class:

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. */
    }
}

For the 2nd Fragment, I want to extend a FragmentActivity as shown below.

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

The 3rd Fragment is same as the first one.

But when I launch the app, it crashes. So, am I wrong in extending FragmentActivity for the class Fragment_2? Is it illegal to extend a FragmentActivity or even an Activity to fragment classes? If not, what is the problem here?

Thanks.


EDIT: After @CommonsWare's answer I updated my class as follows:

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;
}

My final two questions are:

  1. How should I access my R.id.bSend Button in the Fragment_2 class.
  2. Eclipse is giving the suggestion to change getSupportFragmentManager() to getFragmentManager(). Is that change all right?

Thanks!


回答1:


Is it illegal to extend a FragmentActivity or even an Activity to fragment classes?

Fragment is a Java class. Your fragment implementations (for use as pages in your ViewPager) must inherit from Fragment, directly or indirectly.

Activity does not inherit from Fragment. FragmentActivity does not inherit from Fragment. Hence, you cannot inherit from Activity or FragmentActivity and somehow also inherit from Fragment.



来源:https://stackoverflow.com/questions/17414681/can-a-fragment-extend-a-fragment-activity-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!