【问题标题】:Buttons not working according to the code按钮不按照代码工作
【发布时间】:2014-09-25 15:16:31
【问题描述】:
我正在尝试制作一个小应用程序,其中我在 MainActivity 中有 4 个按钮,并且每个按钮都编码为它们的特定类,但是当我按下第一个按钮时,它会重新打开 MainActivity 而不是特定页面和其余按钮不起作用。
如何解决这个问题?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Doubles = (Button) findViewById(R.id.button1);
Singles = (Button) findViewById(R.id.button2);
total = (Button) findViewById(R.id.button3);
score = (Button) findViewById(R.id.button4);
Doubles.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myintent1 = new Intent(MainActivity.this, Doubles.class);
startActivity(myintent1);
}
});
【问题讨论】:
标签:
android
eclipse
button
android-intent
【解决方案1】:
问题是您注册的事件侦听器仅用于双打按钮。
所以为了对其他人做同样的事情
只需使用
Singles.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//stuff here
}
});
total.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//stuff here
}
});
score.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//stuff here
}
});
当您单击 Doubles 时..您正在导航到名为 Doubles.class 的第二页...
检查 Doubles.java 中的 setContentView() 方法,您需要更改为另一个布局
【解决方案2】:
您也可以使用这种方式使用 onClick 属性
//in activity
public void doublesButtonClicked(View v)
{
....
}
//in xml
<Button
android:id="@+id/button_double"
android:onClick="doublesButtonClicked"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginLeft="55dp"
android:layout_marginTop="108dp"
android:layout_toRightOf="@+id/textView1"
android:text="Button" />