2013-07-16 76 views
0

我試圖啓動一個Android的活動名稱「TheGame」從一個按鈕活動「SelectionFragment」誰的ID是「startGame」 的SelectionFragment文件的公共類:意圖開始活動不工作

public class SelectionFragment extends Fragment { 

這是包含意向代碼:

public void startTheGame (View view) { 

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

} 

而這正是我的清單文件看起來像:

<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的如何解決它的建議,它說:

構造意圖(SelectionFragment,類)是未定義

+0

您是否收到錯誤? – buczek

+0

我們只能猜測,因爲你沒有告訴我們問題是什麼。我的猜測是你在onClickListener中調用了這個,在這種情況下用'替換'this''這個' – Simon

+0

對不起@Simon,我現在補充! – Alex

回答

1

onClick屬性必須通過精確的命名到具有相同名稱的公共方法相匹配。你有屬性android:onClick="TheGame"和方法簽名是public void startTheGame (View view)。將onClick屬性值更改爲"startTheGame"

不過,我寧願用View.OnClickListener而不是設置onClick屬性的原因是:

  1. 在長遠來看,則可以重複使用/移動/更改此佈局,你會最終了同樣的錯誤。
  2. 你可能會做一些重構,你可能會意外地改變這個方法,編譯器也不會抱怨。
  3. 在UI和模型之間設置這種類型的鏈接似乎違反了MVC
1

如果你是從你開始的片段活動,試試這個:

public void startTheGame (View view) { 

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

} 
+0

我曾嘗試添加此代碼和LogCat說:java.lang.IllegalStateException:無法找到一個方法TheGame(視圖)在活動類com.alexlamond.higherorlower.MainActivity的onClick處理程序視圖類android.widget.Button與ID 'startGame' 代碼的按鈕: <按鈕 機器人:ID = 「@ + ID/startGame」 機器人:layout_width = 「WRAP_CONTENT」 機器人:layout_height = 「WRAP_CONTENT」 機器人:layout_alignParentBottom =「真「 android:layout_centerHorizo​​ntal =」true「 android:onClick =」TheGame「 android:text =」Start!「 /> – Alex

+0

你有什麼錯誤? –

+1

錯誤就在您的評論之上 – Alex