当我运行应用程序时。按钮拒绝回应。我设置了一个Toast和一个logcat来检查响应。但不是。请帮忙解决
这是我的源代码
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:id="@+id/button"
tools:onClick="topClick" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:id="@+id/button2"
tools:onClick="bottomClick" />
和我的java方法;
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
//Testing the Toast and Log in action
Toast.makeText(this, "Can you see me?", Toast.LENGTH_SHORT).show();
Log.i("info", "Done creating the app");
}
//creating method topclick
public void topClick(View v) {
Toast.makeText(this, "Top button clicked", Toast.LENGTH_SHORT).show();
Log.i("info", "The user clicked the top button");
}
//creating method bottomclick
public void bottomClick(View v) {
Toast.makeText(this, "Bottom button clicked", Toast.LENGTH_SHORT).show();
Log.i("info", "the user clicked the bottom button");
}
}
答案 0 :(得分:0)
替换
tools:onClick
与
android:onClick
两个按钮。
有关更多可帮助您了解需要进行此更改的背景信息,请阅读tools
namespace:
Android Studio支持工具命名空间中的各种XML属性,这些属性支持设计时功能(例如片段中显示的布局)或编译时行为(例如应用于XML资源的缩小模式) 。构建应用程序时,构建工具会删除这些属性,因此不会影响您的APK大小或运行时行为。
答案 1 :(得分:0)
我强烈建议不要使用你的实现,因为你很难知道哪个方法适用于哪个按钮。试试这个。
<强> XML 强>
<Button
android:text="Button"
android:id="@+id/button1" />
<Button
android:text="Button"
android:id="@+id/button2" />
<强> ACTIVITY.JAVA 强>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
Button button01 = (Button)findViewById(R.id.button01);
Button button02 = (Button)findViewById(R.id.button02);
button01 .setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "This is button01", Toast.LENGTH_SHORT).show();
}
});
button02 .setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "This is button02", Toast.LENGTH_SHORT).show();
}
});
}