【发布时间】:2014-01-14 21:21:06
【问题描述】:
我在论坛上阅读了一些帖子,但它们对我不起作用...
我在 Main 中有两个按钮,我希望每个按钮在按下时打开另一个活动...
这是我的代码:
在单击一个按钮时的代码中:
public void onClick(View v)
{
switch (v.getId()) {
case R.id.button1:
Intent intent = new Intent(this, Class1.class);
startActivity(intent);
break;
case R.id.button2:
Intent intentC = new Intent(this, Class2.class);
startActivity(intentC);
break;
}
}
这是我的按钮代码,在 XML 文件中:
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:layout_marginTop="25dp"
android:onClick="onClick"
android:text="Button 2" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="42dp"
android:onClick="onClick"
android:text="Button 1" />
这就是我放在 AndroidManifest(活动名称)上的内容:
<activity android:name="MyActivity1"></activity>
<activity android:name="MyActivity2" ></activity>
有人能说出这里有什么问题或遗漏吗?
当我单击一个按钮时,程序停止...出现一个消息框:“不幸的是,应用程序停止了”
【问题讨论】:
-
你有什么错误?为什么你认为这不起作用?
-
您应该详细说明单击其中一个时发生的情况
-
onClick(View v)是直接定义为主要Activity的一部分的方法,还是OnClickListener的内联/匿名定义的一部分?向我们展示您如何为按钮设置监听器。 -
@Squonk 一开始我认为这是问题,但它在 xml 中声明。
-
@codeMagic :确实是这样——这会教我不要略读。
标签: android button android-activity pressed