![](/img/trans.png)
[英]How to fix attempt to invoke virtual method 'android.view.View androidx.fragment.app.FragmentActivity.findViewById(int)' on a null object reference?
[英]How to cast view and invoke method inside android fragment?
我正在嘗試創建一個應用程序,它將在 android 片段中調用一個方法。 在 Activity 中,我們通常在onCreate()
方法中投射視圖和調用方法。
有沒有辦法在android片段中投射視圖和調用方法? 這個方法應該在哪個函數回調中調用?
如果您使用 New -> Fragment(Blank) 創建片段,並選擇使用它創建布局文件。 視圖轉換應該在 Fragment.java 中為您完成。 如果沒有,這里是如何將片段膨脹到活動中。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//fragment_example is the layout of the fragment
return inflater.inflate(R.layout.fragment_example, container, false);
}
要回答您的問題,您絕對可以在 android 片段中調用方法。 調用函數的位置取決於您使用它們的目的。 很多函數都可以調用
@Override
public void onStart() {}
同樣,如果您按照我指出的方式創建片段,那么這些占位符將已經在 Fragment.java 中為您創建。 還要記住遵循 Fragment, Presenter 規則。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.