简体   繁体   中英

Android - Fragment Views get NULL outside onCreateView

i have a Fragment and the View is stored into a Class variable in onCreateView:

    private FrameLayout mView;
    private TextView countdown;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle bdl) {
            mView = (FrameLayout)inflater.inflate(R.layout.vakit_fragment, container, false);
            countdown = (TextView) mView.findViewById(R.id.countdown);
    ...
            return mView;

    }

both are non-Null here and wont be modified anywhere in my code.

later this is called from the Main Activity:

         MainFragment frag = (MainFragment) mAdapter.getItem(mPager.getCurrentItem());
         if(frag!=null) {
         frag.onSecond();
         }

and in the Fragment:

protected void onSecond(){
    String left=times.getLeft();


    if(countdown!=null)     
        countdown.setText(left);

}

in onSecond both mView and countdown are ever NULL, why? I cant explain it.

metin

我认为您在adapter.getItem()方法中创建了Fragments的另一个实例。

onCreateView is called only when the fragment draws the UI. In this case, onSecond is called before onCreateView , so mView hasn't been inflated yet, which is why it's null. You can get around this by putting the onSecond logic into onCreateView .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM