我有一个带滑动导航的 android Activity (使用 ViewPager 实现)。
public class UberActivity extends FragmentActivity {
ViewPager mViewPager;
protected void onCreate(Bundle savedInstanceState) {
//... some stuff
myfragment1=new MyFragment1();
myfragment2=new MyFragment2();
myfragment3=new MyFragment3();
myfragment4=new MyFragment4();
}
public void onChoiceSelected(){
mViewPager.post(new Runnable(){public void run(){
myfragmen1.update();
myfragmen2.update();
myfragmen3.update();
myfragmen4.update();
}});
}
}
public class Fragment4 extends Fragment {
View v;
@Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container,
Bundle savedInstanceState) {
v=layoutInflater.inflate(R.layout.mylayout,container,false);
return v;
}
public void update(){
((TextView)v.findViewById(R.id.textView1)).setText("new text");
}
我将在 update() 上得到 NullPointerException,除非我事先滑动到它(这样它的布局实际上在调用 update() 之前膨胀)。 这里的问题是 Fragment4 是实例化的,但它的 OnCreateView() 没有被调用。我应该如何检查是否调用了 OnCreateView()?我可以在那里放一个 bool 值,但我认为这不是最佳实践...
最佳答案
只需在“v”周围添加一个 if 语句,检查它是否为 null。
public void update(){
if (v != null) {
((TextView)v.findViewById(R.id.textView1)).setText("new text");
}
}
关于android - 测试一个布局是否已经 "inflated",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15071511/