getActivity() with in FragmentActivity: android

不问归期 提交于 2020-01-02 11:43:14

问题


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??

Code for my class 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

   public abstract class B extends FragmentActivity 
  {


   FragmentAdapter mAdapter;
   ViewPager mPager;
   PageIndicator mIndicator;


 }

回答1:


A FragmentActivity is an instance of Activity (in Java style: 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.

So inside your A (or B) class you could use this code snippet to get the activity instance:

Activity test = (Activity) this;

But if your B class extends Fragment then the getActivity call would have worked.




回答2:


FragmentActivity is an alternate to Activity in support package. Since your class B extends FragmentActivity and later your class A extends class B, therefore your class A is also referring Activity (a.k.a FragmentActivity).

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



来源:https://stackoverflow.com/questions/12693251/getactivity-with-in-fragmentactivity-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!