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.
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.
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().
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With