2015-10-07 82 views
4

當使用Android Studio創建新片段時,它會生成onButtonPressed(Uri)方法,應該如何將它綁定到UI事件中,比如說單擊xml中聲明的按鈕?這種方法打算如何使用?Android Studio片段 - onButtonPressed方法

// TODO: Rename method, update argument and hook method into UI event 
public void onButtonPressed(Uri uri) { 
    if (mListener != null) { 
     mListener.onFragmentInteraction(uri); 
    } 
} 

回答

2

片段得到重視活動中,onFragmentInteraction是一個回調方法,你的活動中使用與片段

交互。例如,下面的活動從您的片段實現接口

public static class YourActivity extends Activity 
     implements YourFragment.onFragmentInteraction{ 
    ... 

    public void onFragmentInteraction(Uri uri) { 
     // Do something with uri 
    } 
} 

但作爲TODO建議

// TODO:將方法,更新參數和鉤子方法重命名爲UI事件

隨意根據您的需要調整或刪除它,如果不需要。例如:

mYourButton.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View arg0) { 
     if (mListener != null) { 
      mListener.onFragmentInteraction(Uri.parse("http://www.google.com")); 
     } 
    } 
}); 
0

例如,你有一個按鈕和一個名爲按鈕:

button.setOnClickLisenter(new View.OnClickListener(){ 
    public void onClick(View view){ 
     // process and construct uri 
     Uri uri = null; 
     onButtonPressed(uri); 
    } 
}; 

你也可以嘗試其他風格來使用onButtonPressed。