我如何知道onCreateView是從外部類調用的?
你需要在 fragment 內部創建介面,並在容器 Activity ( 假設是 MainActivity ) 中實現它。
1 在你的fragment 中創建一個介面://Container activity must implement this interface
public interface OnCreateViewCalledListener {
void OnCreateViewCalled(String someData);
}
2.在容器 Activity ( 假設它是 MainActivity ) 內實現介面,並調用它的方法:public class MainActivity extends AppCompatActivity implements
YourFragment.OnCreateViewCalledListener {
...
@Override
public void OnCreateViewCalled(String someData) {
Toast.makeText(MainActivity.this,"OnCreateView was called and passed" + someData)
}
3 然後你需要檢查MainActivity是否實現了介面回調( 這裡步驟對於使它的正常工作非常重要)://Using onAttach method to check that activity has implemented callbacks
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//Make sure that container activity has implemented
//the callback interface. If not, it throws an exception
try {
mCallback = (OnCreateViewCalledListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+" must implement OnCreateViewCalledListener");
}
}
4,最後你需要在onCreateView中觸發回調:@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mCallback.OnCreateViewCalled("Some useful data");
. . .
}
就是這樣!
編輯:
讓其他類知道onCreateView被調用,請使用MainActivity中的onCreateViewCalled() 回調( 比如 。 使用另一個介面在其他類中觸發回調) 。 也不是強制將數據傳遞到 OnCreateViewCalled ( )