2012-10-23 42 views
0

的我有這樣如何調用活動類中onCreateView片段

public class fragment2 extends Fragment{ 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 


    return inflater.inflate(R.layout.content, container, false); 
} 

代碼}

我想打電話給活動類,而不是佈局。 請幫助我。

+1

請解釋什麼是你想通過調用活動類來實現? –

+0

我的活動類包含一個URL加載,所以如果我調用佈局,那麼它將不會加載URL。所以我想啓動活動類來加載url。 – Shreesha

+0

你爲什麼要打電話給活動課?任何具體原因。 –

回答

0

例如,如果您有稱爲MyActivity和MyFragment的活動和片段,您可以在MyActivity中提供一些公共方法。這在MyFragment#onCreateView() 後,您可以撥打 String layout = ((MyActivity)getActivity()).getMyLayoutLink()

0

你可以在該片段中創建一個接口,然後在活動中實現它。然後,您可以在onAttach()方法的片段中設置偵聽器。這在onCreateView()之前調用。這種模式使得你的代碼可重用,這種技術可以應用於你所使用的所有活動和片段。對於片段示例代碼:

public class YourFragment extends Fragment { 

    private OnItemSelectedListener onClickListener; 

    public interface OnItemSelectedListener { 
     //implement and use this function in your calling activity 
     public void yourItemSelected(String link); 
    } 

    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
     //check that the activity implements the interface 
     if (activity instanceof OnItemSelectedListener) { 
     //set the listener to the calling activity 
     onClickListener = (OnItemSelectedListener) activity; 
     } else { 
     throw new ClassCastException(activity.toString() 
     + " must implement YourFragment.OnItemSelectedListener"); 
     } 
    } 

} 

欲瞭解更多信息請參閱Android文檔: http://developer.android.com/training/basics/fragments/communicating.html
http://developer.android.com/guide/components/fragments.html#Lifecycle

相關問題