首页 > 解决方案 > 在 FragmentPagerAdapter 内的设备旋转后 FindViewById 为空

问题描述

我正在尝试修改 aFragmentPagerAdapter上的UI 元素ViewPager。一切顺利,直到我旋转设备。然后,FindViewById返回null,我无法修改元素。

当我旋转设备时,我必须记住一些操作吗? FragmentPagerAdapter重新创建活动时管理片段? runOnUIThread对此有什么影响吗?我用错了什么?

MainActivity.java


 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        ...

        //detect if it was recreating by rotation device
        if(savedInstanceState != null) {
            rotateEvent = savedInstanceState.getBoolean("rotateEvent");
        }


        // Set up the ViewPager with the sections adapter.
        mViewPager = findViewById(R.id.pager);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setOffscreenPageLimit(5);


        tabLayout = findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        ...
   }

   /**
     * On Received Status update on UI state
     * @param messageReceived: string received
     */
    public void updateReceivedStatus(final String messageReceived) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                    int idElementToUpdate = getResources().getIdentifier(messageReceived, "id", getPackageName());

                    View element = findViewById(idElementToUpdate); // element is null after rotation

                    //Switch type send different message
                    if (element instanceof RadioGroup) {
                        //obtain id string of radiobutton
                        String radioButtonId = message.replace(":", "_");

                   ...
            }
        }
   }

提前致谢。

标签: androidfragmentpageradapterfindviewbyidscreen-rotationandroid-runonuithread

解决方案


推荐阅读