在Android中声明组件崩溃程序

时间:2012-07-29 14:57:13

标签: android components declaration

我试图在android中初始化组件,我搜索互联网并找到了这种类型的声明,但它使我的程序在启动时强制关闭。我做错了什么?

public class MainActivity extends Activity {

    private EditText edit =(EditText) findViewById(R.id.editText3); // This code makes my program come up totally empty and crash in few seconds after being blank.


        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }



        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }


    }

1 个答案:

答案 0 :(得分:1)

在设置布局之前,您无法获得对任何窗口小部件的引用。请尝试以下方法:

public class MainActivity extends Activity {

private EditText edit;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit =(EditText) findViewById(R.id.editText3);
    }

    public void startScan(View view){
        //edit.append(seekBar1.getProgress()+"\n");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


}