[英]Why are my buttons not working in Android Studio?
I am doing A Level computing and I'm trying to make an app for my Comp 4 project. 我正在执行A Level计算,并且正在尝试为我的Comp 4项目制作一个应用程序。 All the other classes i have done with buttons seem to be working fine but the buttons on my main menu are not working. 我使用按钮完成的所有其他类似乎工作正常,但主菜单上的按钮却无法正常工作。
public class MainActivity extends AppCompatActivity {
Button bLogin;
Button bProducts;
EditText etName, etAge, etUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
switch (id) {
case R.id.bLogin:
break;
case R.id.bProducts:
break;
}
return super.onOptionsItemSelected(item);
}
public void ProductsOnClick(View b) {
startActivity(new Intent(".Products"));
switch (b.getId()) {
case R.id.bProducts:
}
}
public void LoginOnClick(View a) {
startActivity(new Intent(".Login"));
switch (a.getId()){
case R.id.bLogin:
}
}
}
This Activity
runs but the buttons on the Options Menu don't work. 该Activity
运行,但是“选项”菜单上的按钮不起作用。
I am using Android Studio to program this. 我正在使用Android Studio对此进行编程。
Because there is nothing to execute when the menu item is selected, change your code like that: 因为选择菜单项时没有什么要执行的,所以请像这样更改代码:
@Override
public boolean onOptionsItemSelected(MenuItem item){
int id= item.getItemId();
switch (id) {
case R.id.bLogin:
startActivity(new Intent(".Login"));
break;
case R.id.bProducts:
startActivity(new Intent(".Products"));
break;
}
return super.onOptionsItemSelected(item);
}
PS: PS:
Make sure that you're using the right Intent constructor, because with Intent(String) you need an action as parameter not an activity name or something else. 确保使用正确的Intent构造函数,因为使用Intent(String),您需要将操作作为参数而不是活动名称或其他名称。
You can use OnClickListener
instead. 您可以改用OnClickListener
。 Put this in your onCreate
: 把它放在你的onCreate
:
bProducts.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(".Products"));
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(".Login"));
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.