Domanda

I tried creating the Base class which will create a TAG string for each Activity which extends it.

So I first created an abstract class

public abstract class First extends Activity {
    static protected String TAG;

    protected void setTag(Activity activity) {
       TAG = activity.getClass().getSimpleName();
    }  
}

Then I create the Base class

public class BaseActivity extends First {

    @Override
    protected void setTag(Activity activity) {
        super.setTag(activity);
    }
}

But how can I now set that each ACtivity which extends BaseActivity sets the TAG variable with its own simple name, instead of BaseActivity simple name?

È stato utile?

Soluzione

If i understood properly what you want to do, this is what you need:

public class SubActivity extends BaseActivity {

    @Override
    protected void setTag(Activity activity) {
        super.setTag(this);
    }
}

However, there's a big possible issue in your code, your abstract class is declaring TAG as static hence, any new activity that calls the method setTag will modify the value of the TAG in "First" class, which is not what you might want, you may want to keep it virtual "non static" so each object created will keep its own version of TAG with the proper name of the class assigned in each SubActivity...

Regards!

Altri suggerimenti

Override onCreate(Bundle savedInstanceState) which is a method you will always call, and there do something like TAG = this.getClass().getSimpleName();

something like

public abstract class First extends Activity {
  protected String TAG;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TAG = this.getClass().getSimpleName();  
  }
}

then

public class BaseActivity extends First {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //continue normally here, you won't even have to remember to call the method  
  }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top