android - 测试一个布局是否已经 "inflated"

标签 android android-layout swipe

我有一个带滑动导航的 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/

相关文章:

android - 后端与托管区别?

android - 边距/填充缩小 ImageView

android - 为 ListView 中的项目设置边距

jquery - 移动设备和平板电脑上粘性标题上的奇怪 flickr

android - 如何从另一个类显示警报对话框并在当前 Activity 中处理它(Android)

java - 使用循环删除某些布局 View

android - 通货膨胀期间应用程序崩溃

android - 在双击和滑动之间切换

ios - 静态 UITableView 中的可滑动单元格

android - 不需要的左边距/填充到工具栏中的 Logo