在 FragmentActivity 中使用 getActivity():android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12693251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getActivity() with in FragmentActivity: android
提问by Shikha Shah
I am using this class A which extends another abstract class (and this abstract class extends FragmentActivity) and in one of my function with in A class I want to get getActivity() for my current activity A. But whenever I use getActivity , It gives me error that getActivity() method is not defined type for my class. Please help me !! How can I achieve this??
我正在使用这个类 A,它扩展了另一个抽象类(并且这个抽象类扩展了 FragmentActivity),并且在我的一个函数中,我想为我当前的活动 A 获取 getActivity()。但是每当我使用 getActivity 时,它都会给出我的错误是 getActivity() 方法不是我的类的定义类型。请帮我 !!我怎样才能做到这一点?
Code for my class A
我的 A 类代码
public class A extends B
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.voicing);
//doing another initializations and stuff//
}
}
code for class B
B类代码
public abstract class B extends FragmentActivity
{
FragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
}
回答by Rolf ツ
A FragmentActivity
is an instance of Activity
(in Java style: FragmentActivity extends Activity
).
AFragmentActivity
是Activity
(在 Java 风格中:)的一个实例FragmentActivity extends Activity
。
So there is no point calling getActivity
because a FragmentActivity
is already an Acivity
, so just calling/using this
will work. Also there is no method called getActivity
in the FragmentActivity
class. In other words your B class is extending an Activity
instance.
因此调用没有意义,getActivity
因为 aFragmentActivity
已经是 an Acivity
,所以只需调用/使用即可this
。也没有叫方法getActivity
在FragmentActivity
类。换句话说,您的 B 类正在扩展一个Activity
实例。
So inside your A (or B) class you could use this code snippet to get the activity instance:
因此,在您的 A(或 B)类中,您可以使用此代码片段来获取活动实例:
Activity test = (Activity) this;
But if your B class extends Fragment
then the getActivity
call would have worked.
但是如果你的 B 类扩展了,Fragment
那么getActivity
调用就会起作用。
回答by waqaslam
FragmentActivity
is an alternate to Activity
in support package. Since your class B
extendsFragmentActivity
and later your class A
extends class B
, therefore your class A
is also referring Activity
(a.k.a FragmentActivity
).
FragmentActivity
为替代,以Activity
在支持包。由于您的class B
extendsFragmentActivity
和后来的class A
extends class B
,因此您class A
也指的是Activity
(又名FragmentActivity
)。
In short, you dont need to call any method. simply use this
keyword to refer to your activity instance.
简而言之,您不需要调用任何方法。只需使用this
关键字来引用您的活动实例。