android - 在 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(":", "_");
...
}
}
}
提前致谢。
解决方案
推荐阅读
- c - 文件读取后将值分配给自定义类型
- java - 如何让 poi 创建 excel 更快?
- kdb - KDB:如何在 kdb-tick 架构中为联合联接序列化表?
- java - 如何将列表变量传递给构造函数/方法
- swift - 如何获得与协议父级的条件协议一致性?
- excel - 将 CSV 导入 Excel(可变宽度数据)导致 #REF 问题
- python - 如何找到所有可能的方法来组合列表中的项目而不重复?
- postgresql - 从暂存中捕获事件以确保只有未取消的事件并更新现有事件
- javascript - 有没有办法将帖子数据动态插入到不同地址加载的html文件中?
- css - CSS Opacity atop Image Overlay