2013-01-16 70 views

回答

55

是,通過調用getActivity與父活動投它來訪問其方法或變量((ParentActivityName)getActivity())

試試這一個其右。

ParentActivityName是父類的名字

+0

如果我們不知道名字怎麼辦?例如:我正在製作sdk,它包含所有片段。我不能讓sdk用戶重新命名他/她的活動。那麼如何在不知道名字的情況下獲得參考? – Kay

+0

您想如何使用該參考? – DcodeChef

+1

我明白了。我的使用案例是在庫中製作n個片段並提供給商家。我不知道他們會使用這些片段的活動。看起來製作一個界面,在活動中覆蓋它並從活動中獲取回調似乎是最佳做法,並且在我的場景中非常有用。 – Kay

7

最正確的方法是讓你Activity實施Interface並使用監聽器。這樣Fragment不與任何特定的Activity保持可重用。進入Fragment

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 

    // This makes sure that the container activity has implemented 
    // the callback interface. If not, it throws an exception 
    try { 
     mCallback = (OnHeadlineSelectedListener) activity; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(activity.toString() 
       + " must implement OnHeadlineSelectedListener"); 
    } 
} 

這樣,你讓Activity聽片段,當它連接到它。

參見:

0

使用getActivity()方法簡單的調用父活動。

CardView cardView = (CardView) getActivity().findView(R.id.your_view);