Android应用关闭时出现null异常

时间:2014-06-18 20:03:52

标签: android

我有一个非常简单的Android应用程序正在构建。我有2个按钮和1个textview。我在fragment_main.xml中以图形方式构建它们。以下是我的完整代码。

  public class MainActivity extends ActionBarActivity {
        TextView tvOut;
        Button btnOk;
        Button btnCancel;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.fragment_main);

            if (savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.container, new PlaceholderFragment())
                        .commit();
            }

            View.OnClickListener oclBtnOk = new View.OnClickListener() {
                public void onClick(View v) {
                    // change text of the TextView (tvOut)
                    tvOut.setText("Button OK clicked");
                }
            };
            btnOk.setOnClickListener(oclBtnOk);
        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        /**
         * A placeholder fragment containing a simple view.
         */
        public static class PlaceholderFragment extends Fragment {

            public PlaceholderFragment() {
            }

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.fragment_main, container, false);
                return rootView;
            }
        }

    }

如果我对这部分代码发表评论,那就很有效。

View.OnClickListener oclBtnOk = new View.OnClickListener() {
                    public void onClick(View v) {
                        // change text of the TextView (tvOut)
                        tvOut.setText("Button OK clicked");
                    }
                };
                btnOk.setOnClickListener(oclBtnOk);

即使我使用setContentView(R.layout.main_activity);所有我的按钮和文本视图出现并且非常困惑为什么即使使用main_activity我的按钮和文本视图也很好。

1 个答案:

答案 0 :(得分:1)

您永远不会为视图指定值。使用findViewById可以使用您在XML布局中提供的ID来获取对视图的引用。

setContentView(R.layout.fragment_main);
// get the views
btnOk = (BUtton) findViewById(R.id.your_button_id);
tvOut = (TextView) findViewById(R.id.another_id);

btnOk.setOnClickListener(...);