我是Android编程的新手。在按钮点击上打开另一个活动时,我面临问题。另外,我正在附上我写的代码。
这是我的 mainActivity 类:
public class MainActivity extends AppCompatActivity{
TextView ed1;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(TextView) findViewById(R.id.textView1);
btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),LoginScreen.class);
startActivity(i);
}
});
}
}
和我的 loginscreen 类如下:
public class LoginScreen extends AppCompatActivity {
TextView tv;
EditText ed1,ed2;
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
tv=(TextView)findViewById(R.id.textView1);
ed1=(EditText)findViewById(R.id.editText1);
ed2=(EditText)findViewById(R.id.editText2);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name= ed1.getText().toString();
String pass=ed2.getText().toString();
if(name.equals(" ")|| pass.equals(" ")){
Toast.makeText(getApplicationContext(),"Required Field",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"Login Successfull",Toast.LENGTH_LONG).show();
}
}
});
}
}
运行此代码后,只有第一类,即MainActivity
运行,然后显示该程序已停止工作的设备。
您的LoginScreen
类问题。您忘了在设置OnClickListener
之前初始化btn1
。
public class LoginScreen extends AppCompatActivity {
TextView tv;
EditText ed1,ed2;
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
tv=(TextView)findViewById(R.id.textView1);
ed1=(EditText)findViewById(R.id.editText1);
ed2=(EditText)findViewById(R.id.editText2);
btn1=(Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name= ed1.getText().toString();
String pass=ed2.getText().toString();
if(name.equals(" ")|| pass.equals(" ")){
Toast.makeText(getApplicationContext(),"Required Field",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"Login Successfull",Toast.LENGTH_LONG).show();
}
}
});
}
}