简体   繁体   中英

How to extend one class to two libraries?

I want to extend two libraries in one class.

 import android.app.ListActivity;
 import android.app.Fragment;

 public class DisplayAll extends ListActivity extends Fragment{}

But java will not support in two extends..How can i do that so that i can extend ListActivity and Fragment in my DisplayAll class .. any help would be appreciated.

Java does not support multiple inheritance.

You can implement multiple interfaces, but not extend multiple classes.

As mentioned, Java does not support multi level inheritance. You can work around that like below:

import android.app.ListActivity;
import android.app.Fragment;

class ListActivityWithFragment extends Fragment{}

public class DisplayAll extends ListActivityWithFragment {}

Multiple Extends class not supported in JAVA.

You can create two different abstract class and use it like as below.

Your Main Class :

public class DisplayAll extends YourClass1
{

}

Your abstract Class1 :

public abstract class YourClass1 extends YourClass2
{
}

Your abstract Class2 :

public abstract class YourClass2 extends Fragment
{
}

Note : You can't extend Activity and Fragment for single class.

Java does not support for Multiple Inheritance then you can't do it in any way.

If you would like to work with a ListActivity and a Fragment you should check the ListFragment or the support-v4 version and the best way is to use:

public class DisplayAll extends ListFragment{

}

However currently I suggest you c hecking the last guidelines and support libraries in Android .
A good way to work is to use an AppCompatActivty and a simple RecyclerView to display a list.

Best shot is nesting the classes ie declare the class extending Fragment inside the class extending the class extending ListActivity. This way, inside the nested class extending Fragment you will be able to use everything you create in the class extending ListActivity

Example:

 import android.app.ListActivity;
 import android.app.Fragment;

 public class DisplayAll extends ListActivity {
   //ListActivity related stuff here
   public class DisplayAllFragment extends Fragment {
       //Fragment related stuff here
       //You can also access the containing class extending ListActivity's stuff here
   }
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM