Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested inner Activity class in android

Is declaring a class that extends Activity inside another Activity class possible? If it is, how would I register that class in the manifest? Also, is that something that can be reasonably done or is it a bad idea?

I was thinking of something like

class ListClass extends ListActivity{

    ...
    ArrayList items;

    class ItemClass extends Activity{

        ...
        Item item;

        @Override
        onCreate(){
            Integer pos = getIntent().getExtras().getInt("pos");
            item = items.get(pos);
        }
    }

    @Override
    onItemClick(int position){

        startActivity(new Intent(this, ItemClass.class).putExtra("pos", position));

    }
}

Note the syntax isn't 100% correct obviously, mostly pseudocode.

like image 658
Falmarri Avatar asked Oct 29 '10 18:10

Falmarri


People also ask

What is the difference between inner class and nested class?

Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.

What is inner class in Android?

Inner classesA nested class marked as inner can access the members of its outer class. Inner classes carry a reference to an object of an outer class: class Outer { private val bar: Int = 1 inner class Inner { fun foo() = bar } } val demo = Outer().

What is the use of nested class in Java?

As mentioned in the section Nested Classes, nested classes enable you to logically group classes that are only used in one place, increase the use of encapsulation, and create more readable and maintainable code.


2 Answers

Yes, it does work -- it is just another class -- you just need to declare your activity using inner class notation in AndroidManifest.xml:

<activity android:name=".ListClass$ItemClass"/>

Seems to work fine for me, but perhaps when this question was asked, it wasn't supported in older versions of Android?

Not sure WHY you'd want to do this, but you can.

like image 64
DustinB Avatar answered Sep 24 '22 13:09

DustinB


No, that's not possible. After all, the Android operating system will need to instantiate the Activity if it is started at any point (say, if you start it through an intent), and it's impossible to instantiate an ItemClass without a parent ListClass.

Remember that each Activity is completely independent and can be started at any point through an intent.

like image 28
EboMike Avatar answered Sep 24 '22 13:09

EboMike