在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:27:28  来源:igfitidea点击:

getActivity() with in FragmentActivity: android

androidandroid-activityandroid-fragmentactivity

提问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 FragmentActivityis an instance of Activity(in Java style: FragmentActivity extends Activity).

AFragmentActivityActivity(在 Java 风格中:)的一个实例FragmentActivity extends Activity

So there is no point calling getActivitybecause a FragmentActivityis already an Acivity, so just calling/using thiswill work. Also there is no method called getActivityin the FragmentActivityclass. In other words your B class is extending an Activityinstance.

因此调用没有意义,getActivity因为 aFragmentActivity已经是 an Acivity,所以只需调用/使用即可this。也没有叫方法getActivityFragmentActivity类。换句话说,您的 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 Fragmentthen the getActivitycall would have worked.

但是如果你的 B 类扩展了,Fragment那么getActivity调用就会起作用。

回答by waqaslam

FragmentActivityis an alternate to Activityin support package. Since your class BextendsFragmentActivityand later your class Aextends class B, therefore your class Ais also referring Activity(a.k.a FragmentActivity).

FragmentActivity为替代,以Activity支持包。由于您的class BextendsFragmentActivity和后来的class Aextends class B,因此您class A也指的是Activity(又名FragmentActivity)。

In short, you dont need to call any method. simply use thiskeyword to refer to your activity instance.

简而言之,您不需要调用任何方法。只需使用this关键字来引用您的活动实例。