使用视图时,活动片段的空指针运行方法



My Fragment

public class CustomFrag extends Fragment {
    private Button btn;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.button_fragment, container, false);
        btn = (Button)view.findViewById(R.id.button1);
        return view;
    }
    public void sendItem(String item) {
        btn.setText(item);
    }
}

在我的活动

public void loadFragment(String data) {
    // Load up new fragment
    Fragment fragment = new CustomFrag();
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    transaction.add(R.id.contentFragment, fragment, "custFrag");
    transaction.addToBackStack("custFrag");
    transaction.commit();
    // Required before calling fragment methods 
    getSupportFragmentManager().executePendingTransactions();
    // Load fragment with data
    CustomFrag frag = (CustomFrag) getSupportFragmentManager().findFragmentByTag("custFrag");
    frag.sendItem(data);
}

我得到一个空指针异常任何时候我试图使用我的片段的视图。如果我尝试在方法中加载视图,它将无法工作

。内部sendItem ()

btn = (Button)getView().findViewById(R.id.button1);

我的布局(button_fragment)包含按钮:

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

因为您已经执行了事务并不意味着片段实际上已经创建了它的视图。这就是为什么btn仍然是空的。

要将数据从活动传递到片段,使用参数bundle:

Fragment fragment = new CustomFrag();
Bundle args = new Bundle();
args.putString("item", data);
fragment.setArguments(args);

然后,在onCreateView中:

btn = (Button)view.findViewById(R.id.button1);
btn.setText(getArguments().getString("item"));

查看实例化新的Android Fragment问题和第一个答案的最佳实践

这里的问题是,当sendItem(…)被调用时,片段的布局尚未绘制。这意味着btn在这一点为零。相反,您应该这样做(参见http://developer.android.com/guide/components/fragments.html):

)。
public class CustomFrag extends Fragment {
    private Button btn;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.button_fragment, container, false);
        btn = (Button)view.findViewById(R.id.button1);
        btn.setText(getArguments.getString("item"));
        return view;
    }
}

public void loadFragment(String data) {
    // Load up new fragment
    Fragment fragment = new CustomFrag();
    Bundle args = new Bundle();
    args.putString("item", data);
    fragment.setArguments(args);
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    transaction.add(R.id.contentFragment, fragment, "custFrag");
    transaction.addToBackStack("custFrag");
    transaction.commit();
    // Required before calling fragment methods 
    getSupportFragmentManager().executePendingTransactions();
}

编辑:njzk2更快,但我希望我给的细节能进一步帮助你。无论如何,他给出的链接很好地解释了为什么你应该这样做

相关内容

最新更新