从基类获取当前的活动名称 [英] Getting current Activity name from base class
问题描述
如何在基类中获取当前活动的名称. 假设我有一个基本活动类BaseActivity:
How can I get the name of the current activity in the base class. Suppose I have a base activity class BaseActivity :
class BaseActivity extends AppCompatActivity
{
...
String getCurrentActivityName() {
....
}
...
}
现在我还有另外2个课程
Now I have 2 other classes
class Activity1 extends BaseActivity
{
....
}
class Activity2 extends BaseActivity
{
....
}
也许还有更多扩展BaseActivity的活动,为简便起见,我在这里使用了2.
There maybe many more activities extending BaseActivity, for brevity I have used 2 here.
我不确定如何在基类中实现getCurrentActivityName()方法.它应该返回一个包含当前活动名称的字符串.
I am not sure how to implement getCurrentActivityName() method in the base class. It should return a String containing the name of the current activity.
由于某些原因,我无法编辑Activity1和Activity2.
EDIT : For some reasons I cannot edit Activity1 and Activity2.
推荐答案
创建新的活动类时,应将类名添加到构造函数中,然后在尝试时使用getCurrentActivityName
方法获取它
When creating a new activity class you should add classname to the constructor and then get it with getCurrentActivityName
method as you were trying
class BaseActivity extends AppCompatActivity
{
protected String className;
public BaseActivity() { this.className = "BaseActivity"; }
String getCurrentActivityName() {
return this.className;
}
...
}
class Activity1 extends BaseActivity
{
protected String className;
public Activity1() { this.className = "Activity1"; }
}
class Activity2 extends BaseActivity
{
protected String className;
public Activity2() { this.className = "Activity2"; }
}
然后致电
BaseActivity baseActivity = new BaseActivity();
baseActivity.getClassname(); // returns "BaseActivity"
Activity1 activity1 = new Activity1();
activity1.getClassname(); // returns "Activity1"
或者,如果您只是想知道当前活动名称,请使用.就这么简单
Or if you just want to know the current activity name use . It's as simple as that
this.getClass().getSimpleName()
这篇关于从基类获取当前的活动名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!