2014-02-22 23 views
0

我是新來的android開發。我有幾個帖子和教程,但我不太理解使用/設置意圖。使用意圖與按鈕事件

我創建了一個應用程序,以獲得更好的理解,但我不能讓代碼工作。 我的思維過程是如下

  1. 我設置2個活動與片段。
  2. 我的主要片段我加了一個按鈕,即一旦點擊它進入另一個活動頁面

問題:當我使用意圖做我所說的片段或活動?

我的代碼:

import android.content.Intent; 
    import android.os.Bundle; 
    import android.support.v4.app.Fragment; 
    import android.view.LayoutInflater; 
    import android.view.View; 
    import android.view.ViewGroup; 
    import android.widget.Button; 


    public class PlanMeMainFragment extends Fragment { 

    private Button mNewButton, mExistingButton; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.planme_main_fragment, parent, false); 
    return v; 


    mNewButton = (Button)v.findViewById(R.id.new_event_button); 
    mNewButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent myIntent = new Intent(PlanMeMainFragment.this, NewEventSetupFragment.class); 
      startActivity(myIntent); 
     } 
     }); 
    } 
    } 

我有我的清單設置爲

 <activity 
     android:name=".PlanMeMainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <activity 
     android:name=".NewEventSetupActivity"> 

    </activity> 

回答

0

您無法從片段調用活動。作爲調用類,您需要設置承載片段的活動。你可以通過getActivity()來獲得。 如果你想打電話從第一片段的第二活動(即位於你的第一個活動),你去這樣的:

Intent myIntent = new Intent(getActivity(), SecondActivity.class); 
getActivity().startActivity(myIntent); 

在你剛纔援引可以實例化的片段就像​​你這樣做活動的第一。但是你確定你需要第二個活動嗎?你可以在你的活動中放置兩個碎片,並將第一個碎片替換爲第二個碎片(如果你不知道的話,只需要簡單提供一個碎片)。

+0

當我改變行上面(@tritop),我的行說mButton =(Button)v.findViewById(R.id.new_event_button;給出了一個無法訪問的語句錯誤?這是什麼意思? – hozdaman

+0

@hozdaman:這就是你的下一個錯誤,我沒有看到第一個地方,你正在返回v之前,這意味着下面的代碼永遠不會到達,你需要將該返回v;行放在底部,緊挨着onCreateView()。它始終是你在onCreateView中做的最後一件事 – tritop

+0

@ tritop - 非常感謝你的幫助,就是這樣。 – hozdaman

0
Intent myIntent = new Intent(PlanMeMainFragment.this, NewEventSetupActivity.class); 

要切換活動之間,你拿活動。

+0

@hozdaman那麼這是什麼問題? – Raghunandan