2014-10-29 86 views
0

我似乎無法從我的Button開始一個新的Activity,我在這裏搜索的答案,但似乎無法解決問題。我希望有人有一個簡單的解決方案。提前致謝。按鈕onClick錯誤...找不到方法

以下是錯誤:

E/AndroidRuntime﹕ FATAL EXCEPTION: main 
java.lang.IllegalStateException: Could not find a method openSearch(View) in the 
activity class dk.mathias.splitcab.MainActivity 
for onClick handler on view class android.widget.Button with id 'btnStartSearch' 

MainActivity.java

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

} 

public void openSearch(){ 
    Intent openSearchIntent = new Intent(MainActivity.this, StartSearch.class); 
    startActivity(openSearchIntent); 
} 

AndroidManifest.xml中

<activity 
     android:name=".StartSearch" 
     android:label="@string/title_activity_start_search" > 
     <intent-filter> 
      <action android:name="dk.mathias.splitcab.STARTSEARCH" /> 

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

activity_main.xml中

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/StartSearch" 
    android:id="@+id/btnStartSearch" 
    android:layout_alignParentBottom="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:layout_alignRight="@+id/tvWelcome" 
    android:layout_alignEnd="@+id/tvWelcome" 
    android:onClick="openSearch" 

    /> 

StartSearch.java

public class StartSearch extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_start_search); 
    } 
} 
+0

您的StartSearch.class活動在哪裏? – 2014-10-29 13:18:36

+1

那麼會發生什麼?錯誤,例外,日誌? – Yazan 2014-10-29 13:19:47

+0

它看起來正確... – 2014-10-29 13:21:01

回答

5

的問題是在你的方法簽名

public void openSearch(){ 

它應該有一個,也是唯一一個PARAM,這是一個View

將其更改爲

public void openSearch(View v){ 

v顯然可以是你希望它是什麼,但你應該讓有意義的東西像vview,等...

From the Docs

In order for this to work, the method must be public and accept a View as its only parameter.

See this answer有關添加Buttons和的更詳細說明

+0

謝謝你的回答。 – 2014-10-29 13:34:17

1

首先作個參考,以您的按鈕

search = (Button) findViewById(R.id.btnStartSearch); 

然後實現的onClick聽者的按鈕,如下

 search.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      Intent openSearchIntent = new Intent(MainActivity.this, StartSearch.class); 
      startActivity(openSearchIntent) 
     } 
    }); 

確保您從XML文件中刪除此行

android:onClick="openSearch" 
+0

你爲什麼會這麼建議?一切都很好,OP的方式除了缺少方法參數 – codeMagic 2014-10-29 13:26:01

+0

@codeMagic - 你的回答非常好,我也有+1我的意圖建議這是知道onClick監聽器的實現 – 2014-10-29 13:28:25

+1

我我並不關心+1,關鍵是你聽起來好像OP在做這件事的方式做錯了。我一直用'onClick'看到這個。我認爲我們不應該以另一種方式告訴OP,而不必解釋什麼是錯誤的。這很混亂。 – codeMagic 2014-10-29 13:30:32