2014-02-19 74 views
0

我有一個類文件MainActivity,我想切換到Testing.class文件。所以這是下面的代碼。如何使用Intent切換到活動?

public static class MyFragment extends Fragment 
{ 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) 
    { 


     View rootView = inflater.inflate(R.layout.xyz, container, false); 

     final TextView tt=(TextView) rootView.findViewById(R.id.txt); 

     Button button=(Button) rootView.findViewById(R.id.btn1); 


     View.OnClickListener sx = new OnClickListener() 
     { 

      public void onClick(View v) 
      { 

       call(); 

      } 

     }; 

     button.setOnClickListener(sx); 


     return rootView; 


    } 


     private void call() 
     { 

        // Here getting the Error // 

       Intent intent = new Intent(MainActivity.this, Testing.class); 



      startActivity(intent); 


     } 



    } 

所以,這是上面的代碼,我想切換到所謂的測試但新的類文件

我面臨了人爲錯誤的:類型MainActivity沒有外圍實例是在訪問範圍

我想創建一個新的靜態類,在MainActivity內創建一個名爲MyFragment的問題。

所以,請幫助我,並給我一些很好的解決方案。

回答

1

好,所以你不能調用MainActivity.this,因爲你在片段類。您必須以不同的方式訪問上下文。如

getActivity() 

它返回與片段關聯的活動。該活動是上下文(由於活動擴展上下文)

+0

感謝很多人之前返回null。它工作得很好。你拯救我的一天。 – animation123

+0

沒問題記得點贊並選擇答案! – Dave

+0

Yaa Man ...我已經完成.... – animation123

0

您可以使用您的片段內getActivity()方法,但要小心,這種方法可能的情況下,調用它的越來越onActivityCreated()方法