如何在片段中创建活动?

时间:2014-03-08 10:26:47

标签: android android-layout android-fragments android-button

这是代码。但有错误。 错误行已标记。并且错误是nullpoinerexception。有人可以帮帮我吗?

public class SettingFragment extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View setting_layout = inflater.inflate(R.layout.setting_layout, container, false);


        Button buttonClickChangeArea = (Button) setting_layout.findViewById(
                R.id.Button_setting_settingarea);
 <=error==> buttonClickChangeArea.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getActivity(), SetAreaActivity.class);
                // Bundle extras = new Bundle();
                // intent.putExtras(extras);
                getActivity().startActivity(intent);

            }
        });

        return setting_layout;

    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


}

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试重命名您的观点。它与您的布局名称相同,因此从

更改
View setting_layout = inflater.inflate(R.layout.setting_layout, container, false);

View view = inflater.inflate(R.layout.setting_layout, container, false);

Button buttonClickChangeArea = (Button) view.findViewById(
            R.id.Button_setting_settingarea);

必须确保您的Button位于id为Button_setting_settingarea的setting_layout.xml文件中。

还要确保您的manifest.xml文件中已注册 SetAreaActivity