我偶然发现的一件事是,当我将代码放入 postDelayed 处理程序中时,它工作正常。在没有 postDelayed 处理程序的情况下如何使其工作?
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
final SlideFragment fragment = new SlideFragment();
if (position == 3){
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
fragment.btnStart.setVisibility(View.VISIBLE);
}
},0);
}
return fragment;
}
@Override
public int getCount() {
return NUM_PAGES;
}
}
最佳答案
问题是您的 View 可能无法按时创建,以便您调用它们的 setVisibility 。理想情况下,您会在创建 fragment 时传递一个参数,并从中对 fragment 进行操作。
if (position == 3){
final SlideFragment fragment = new SlideFragment();
Bundle bundle = new Bundle();
bundle.putBoolean("BUTTON_VISIBILITY", true);
fragment.setArguments(bundle);
}
然后在你的 fragment 中:
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle= getArguments();
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
btnStart = view.findViewById(R.id.id_of_your_button);
if(bundle!=null){
if(bundle.getBoolean("BUTTON_VISIBILITY", false)){
btnStart.setVisibility(View.VISIBLE);
}
}
return view;
}
编辑
您可以使用 onViewCreated 来确保所有内容都已创建:
public View onCreateView(LayoutInflater inflater, ViewGroup containerObject, Bundle savedInstanceState){
return inflater.inflate(R.layout.your_fragment_layout, container, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle bundle= getArguments();
btnStart = view.findViewById(R.id.id_of_your_button);
if(bundle!=null){
if(bundle.getBoolean("BUTTON_VISIBILITY", false)){
btnStart.setVisibility(View.VISIBLE);
}
}
}
关于java - 我想让 ViewPager 到达第 4 页时可见按钮,但出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50876616/