繁体   English   中英

意图启动活动不起作用

[英]Intent To Start Activity Not Working

我试图从活动'SelectionFragment'开始一个Android活动名称'TheGame',其中一个ID为'startGame'的按钮SelectionFragment文件的公共类是:

public class SelectionFragment extends Fragment {

这是包含Intent的代码:

public void startTheGame (View view) {

    Intent intent = new Intent(this, TheGame.class);
    startActivity(intent);

}

这就是我的Manifest文件的样子:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alexlamond.higherorlower"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@drawable/highlowlogo"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.alexlamond.higherorlower.MainActivity"
        android:label="@string/app_name" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/app_id" />

    <activity android:name="com.facebook.LoginActivity" >
    </activity>
    <activity
        android:name="com.alexlamond.higherorlower.TheGame"
        android:label="@string/title_activity_the_game" >
    </activity>
</application>

我的问题是,当我得到Eclipse关于如何解决它的建议时,Intent将无法工作,它说:

构造函数Intent(SelectionFragment,Class)未定义

如果您从片段开始活动,请尝试以下操作:

public void startTheGame (View view) {

Intent intent = new Intent(getActivity(), TheGame.class);
startActivity(intent);

}

您的onClick属性必须通过精确命名到具有相同名称的公共方法来匹配。 你有属性android:onClick="TheGame" ,方法签名是public void startTheGame (View view) onClick属性值更改为"startTheGame"

但是,我宁愿使用View.OnClickListener而不是设置onClick属性,因为:

  1. 从长远来看,您可以重复使用/移动/更改此布局,最终会出现相同的错误。
  2. 您可能会进行一些重构,您可能会意外更改此方法,编译器不会抱怨。
  3. 在UI和模型之间设置这种类型的链接似乎违反了MVC

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM