android how to create my own Activity and extend it?

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.

Leave a Comment