【问题标题】:Android: Switching to another activity using a button event?Android:使用按钮事件切换到另一个活动?
【发布时间】:2011-08-27 11:22:53
【问题描述】:

我想使用一个按钮将当前活动更改为 android 中的另一个活动。但是,每当我单击该按钮时,eclipse 调试透视图都会出现错误“找不到源”。这是我用来改变活动的函数

public void toManager(){
    Intent i = new Intent(getApplicationContext(), DegreeActivity.class);
    startActivity(i);
}

在我的 xml 文件中,按钮有一个 onClick 监听器。这是xml

<Button
    android:id="@+id/btn_toDegree"
    android:text="@string/btn_toDegree"
    android:textSize="13pt"
    android:layout_centerVertical="true"
    android:gravity="center"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_marginLeft="15dip"
    android:layout_marginRight="15dip"
    android:onClick="toManager"  <!-- This line -->
    />  

如果我在第一个活动的onCreate() 块中调用toManager() 函数,它会毫无错误地切换到下一个活动。但是,当我尝试使用按钮进行切换时,它不起作用。

【问题讨论】:

    标签: android android-button


    【解决方案1】:

    点击处理程序必须如下所示:

    public void toManager(View view) {
        Intent i = new Intent(getApplicationContext(), DegreeActivity.class);
        startActivity(i);
    }
    

    来自Button 文档:

    现在,当用户点击按钮时,Android 系统会调用 活动的selfDestruct(View) 方法。为了使其发挥作用, 方法必须是公共的,并且接受 View 作为其唯一参数。

    【讨论】:

    • 你可以忽略它,但是handler的签名必须是public void methodName(View)。那是因为 Android 使用反射来查找处理程序,它可以找到您的方法,因为它有错误的签名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    相关资源
    最近更新 更多