为什么Android应用程序在类的开头使用findViewById(R.id.******)初始化变量时崩溃了?

000*_*000 2 android findviewbyid

我只是测试输入/输出,没有特殊用途,这是最后一个成功运行的代码:

public class MainActivity extends AppCompatActivity
{

/*
EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
TextView welcome = (TextView)findViewById(R.id.textView_Welcome);
Button login=(Button)findViewById(R.id.button_Login);
Button anotherLogin=(Button)findViewById(R.id.button_Login_Another);

public void doLoginOnClick(View v)
{
    String s1=username.getText().toString();
    inputdata.setText(s1);
}

*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
} 

}
Run Code Online (Sandbox Code Playgroud)

我试图捕获组件的id

findViewById(R.id.***)

正如您所看到的,我在代码的最开头处将此代码放在注释中.

EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
TextView welcome = (TextView)findViewById(R.id.textView_Welcome);
Button login=(Button)findViewById(R.id.button_Login);
Button anotherLogin=(Button)findViewById(R.id.button_Login_Another);
Run Code Online (Sandbox Code Playgroud)

如果我删除上面的注释并运行它(在模拟器和真实设备中),程序立即崩溃,我很惊讶这里有什么问题?

即使我试图使用构造函数初始化相同的东西.

但如果我把它放在onCreate()里面没有崩溃?为什么?

我试图获取用户名和密码的信息,并在textView_Inputdata使用中将其显示在textview中

EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
inputdata.setText(username.getText.toString()+" "+password.getText.toString());
Run Code Online (Sandbox Code Playgroud)

有更好或更简单的方法吗?

laa*_*lto 6

初始化实例本身时初始化实例成员变量.这太早了findViewById()

以前onCreate()你的活动还没有一个WindowfindViewById()内部的需要.之前setContentView()(你应该打电话onCreate()),也没有找到任何意见.

因此onCreate(),在之后和之后初始化视图引用setContentView().