android how to create my own Activity and extend it?
Asked Answered
M

4

70

I need to create a base class that extends Activity which does some common tasks in my application and extend my activities from it,in the following form:

public BaseActivity extends Activity{....}

public SubActivity extends BaseActivity{...}

in SubActivity I need to give values to some variables and UI components defined in BaseActivity, I may need to define a different layout for SubActivity according to some flag value, also(in SubActivity ) I want to execute asyncTask that is defined in BaseActivity.

is this possible? if yes, is there any tutorial that may help? thank you in advance

Morgan answered 11/1, 2012 at 14:48 Comment(0)
S
139

What exactly are you trying to achieve? Having two different activities with a common ui, except for some variables or parts of the layout?

In this case, I suggest having a base abstract activity, and two concrete inherited subclasses. You define all the common behaviour in the base activity, and have abstract methods for the differences, which you then override in your actual implementations.

For example, for two activities with different layout resources:

public abstract class BaseActivity extends Activity {
    @Override
    public void onCreate(bundle) {
        super.onCreate(bundle);
        setContentView(getLayoutResourceId());
    }

    protected abstract int getLayoutResourceId();
}

public class Activity1 extends BaseActivity {
    @Override
    public void onCreate(bundle) {
        super.onCreate(bundle);
        // do extra stuff on your resources, using findViewById on your layout_for_activity1
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.layout_for_activity1;
    }
}

You can have a lot more abstract methods, for every bit you want specific to your subclasses.

Doing that is, in my opinion, a lot better than having a concrete subclass to a concrete superclass: that can lead to many problems and is usually difficult to debug.

Sheikh answered 11/1, 2012 at 15:2 Comment(12)
No problem P) Bear In mind I coded that quickly in the StackOverflow editor, there may be syntax errorsSheikh
thanks, i took the idea and applied it to other functions, data to pass and AsyncTask in BaseActivity, it worked just fine.Morgan
Yes, I also have a lot of stuff in the Base Activities of my projects. In fact I usually spend a bit of time trying to think about whether it should go in the base activity or the (custom) application. If it has to do with layout, then activity, if not, then application.Sheikh
Qusetion : can you please share a Scenario where i can use it .Containerize
No need to add base activity to manifest since it's abstract and you won't be instantiating it.Mahala
@Sheikh am using the method you described but when I add a button in my subclass of BaseActivity, I get null.Do you know why this is so?Mahala
Hey, so I put an onPause method in my BaseActivity. For some reason, the onPause gets called every time the user switches an activity. Say I switch between public class myClass extends BaseActivity and switch to public class myOtherClass extends BaseActivity. This switch is unnecessarily executing onPauseJuggle
How can I fix this issue? I really appreciate your help. My question in detailJuggle
Using setContentView in an abstract Activity limits flexibility if a subclassed Activity requires a different layout. It's setting the Content View (something that is stand-alone) to an Activity that is not stand-alone.Brest
SIr, I tried to implement the same way but I am having white screen instead of displaying layout. Can you me help me please. #35415656Leatherneck
In my opinion overriding and declaring setContentView() final to initialize the common stuff in base activity is much better approach...User can work without being getting worried about overriding oncreate() of the Base Activity...Frecklefaced
thanx, saved my time. +1Cherri
S
8

This question already has very good answers.
However. my answer is for those people who are looking for some working example.
Here is the full working -> CODE

enter image description here
We are not doing anything new here, it is just like any other inheritance scenario (You want some common behavior at multiple places but you want to write that behavior only once).

ADVANTAGE: It does provide better code readability, maintainability and blah blah. But are not after these -ibility, They won't matter to you if your brain runs like a gazelle.
We are after the real power of inheritance “CONTROL”. (That’s what happens in real life too. Parent controlling child :) ) .

In my example, I have two Activities MainActivity and OtherActivity. Both Activities has a different layout but I want both of them to start with some animation or some welcome message.

Our first task is to find out the common behavior. here -> Start Activity with animation.
We have found the common “thing”, now we will write that behavior in BaseClass (AnimationActivity).
MainActivity and OtherActivity will inherit AnimationActivity.

So the code would look like `

BaseActivity

AnimationActivity {

  startAnimation()
  {  
    ....  
  } 
}

Child Activities

MainActivity extends AnimationActivity{

}

OtherActivity extends AnimationActivity{

}

This design approach provides a lot of Control and Flexibility (POWER OF MODIFIER).

1) CONTROL: Keep animation method inside onCreate() When you decide that Activities should be started with Animation. Keep your method inside onCreate(Bundle bundle) method. Now just by changing the modifier, you can control the child Activities.
If you keep modifier as
final: Child activities will start with parent Animation.
abstract: Child activities will have to give their own animation.
no modifier: Child activities can have their own animation by overriding animation method, Otherwise the child will have parent animation.

2)Flexibility: Don't keep animation method inside onCreate() You can provide child activities flexibility by not keeping animation method inside onCreate(Bundle bundle). Now activities can have the flexibility to have parent Animation or their own animation or no animation at all.
Hope it helps.
Happy learning.

`

Schlemiel answered 5/7, 2017 at 16:50 Comment(0)
A
5

Yes you can, you should just keep in mind the basic inheritance rules. You will inherit the inner AsyncTask activity and the properties defined in the BaseActivity if you make them protected instead of private. From what I see now I think you should make BaseActivity an abstract class, as only instances of subActivities will be really used.

You should just start and try it, it'll come and work easier than you think. If you stumble upon any problems, just ask.

Araceli answered 11/1, 2012 at 14:54 Comment(0)
R
2

I have found an easier way to @Guillaume's solution. Set ContentView only once in your BaseActivity and do not set it in the activities that extend it:

public abstract class BaseActivity extends Activity {
    @Override
    public void onCreate(bundle) {
        super.onCreate(bundle);
        setContentView(activity_main);
    }
}

public class Activity1 extends BaseActivity {
    @Override
    public void onCreate(bundle) {
        super.onCreate(bundle);
        // setContentView(activity_activity1)  // Do NOT call this.
    }
}
Reading answered 17/2, 2016 at 13:51 Comment(1)
seem legit, but i have some concerns, user will be left to use only one layout...if i have 3 views common in 3 diff activities but other than that all the layouts are different then i guess this solution defeats the purpose....Frecklefaced

© 2022 - 2024 — McMap. All rights reserved.