我正在尝试使用一个布局和两个按钮制作一个简单的应用程序,这些按钮将更改布局文本。但我找不到解决 android:onClick 不执行的原因。在尝试了一个不起作用的 OnClickListener 之后,就像他们在这里所做的那样:android:onClick XML 属性与 setOnClickListener 有何不同?
我已经阅读并遵循了 AAndroid SDK 网站上的教程:http: //developer.android.com/reference/android/widget/Button.html
这是我的 XML 代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/maintext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.00"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2" />
这是我的Java代码:
public class MainActivity extends Activity implements OnClickListener{
TextView label1;
int stage;
Button button1, button2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
label1 = new TextView(this);
TextView label1 = (TextView) findViewById(R.id.maintext);
stage = 1;
label1.setText("hello " + stage);
Log.d("HiThereActivity", "THIS IS DEBUG OUTPUT TO LOGCAT"); //working
button1 = new Button(this);
button2 = new Button(this);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
button1_click(v);
Log.d("button1 working", "THIS IS DEBUG OUTPUT TO LOGCAT"); //not appearing
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
button2_click(v);
Log.d("button2 working", "THIS IS DEBUG OUTPUT TO LOGCAT"); //not appearing
}
});
}
public void button1_click(View v) {
stage = 2;
label1.setText("hello " + stage);
Log.d("b1click", "THIS IS DEBUG OUTPUT TO LOGCAT"); //not appearing
}
public void button2_click(View v) {
stage = 3;
label1.setText("hello " + stage);
Log.d("b2click", "THIS IS DEBUG OUTPUT TO LOGCAT"); //not appearing
}
@Override
public void onClick(View v) {
Log.d("wrong method", "THIS IS DEBUG OUTPUT TO LOGCAT"); // not appearing
}}
因此,我得到的唯一 Logcat 消息是 OnCreate 方法中的消息。阶段变量始终保持在 1 并且当我单击按钮时不会改变。然而,这些按钮会为点击设置动画,因此它必须是 OnClick 或标签本身不起作用。
模拟器运行的图片:http: //i.stack.imgur.com/ioUoD.png
提前致谢!