2010-07-01 49 views
0
package com.iperetz1.android.testbutton1; 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 

public class TestButton extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Button test2 = (Button)findViewById(R.id.test2);  
     test2.setOnClickListener(new OnClickListener() 
     { 
      @Override 
      public void onClick(View v) 
      { 
       setContentView(R.layout.test2);; 
      } 
     }); 

     Button other = (Button)findViewById(R.id.backmain);  
     other.setOnClickListener(new OnClickListener() 
     { 
      @Override 
      public void onClick(View v) 
      { 
       setContentView(R.layout.main);; 
      } 
     }); 
    } 
} 

main.xls錯誤「的Android(項目名稱)已意外停止

<?xml version="1.0" encoding="utf-8"?> 
<AbsoluteLayout 
android:id="@+id/widget0" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
xmlns:android="http://schemas.android.com/apk/res/android" 
> 
<Button 
android:id="@+id/test2" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="test2" 
android:layout_x="24px" 
android:layout_y="165px" 
> 
</Button> 
</AbsoluteLayout> 

test2.xml

<?xml version="1.0" encoding="utf-8"?> 
<AbsoluteLayout 
android:id="@+id/widget0" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
xmlns:android="http://schemas.android.com/apk/res/android" 
> 
<Button 
android:id="@+id/backmain" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="backmain" 
android:layout_x="24px" 
android:layout_y="165px" 
> 
</Button> 
</AbsoluteLayout> 
+0

這很簡單,因爲您不能這麼做(更改內容視圖) – Cristian 2010-07-01 19:54:29

+0

可以嗎發給我我在哪裏可以找到如何做到這一點的權利 – iperetz1 2010-07-01 20:01:14

+0

使用logcat通常會幫助排查這些類型的錯誤。 http://developer.android.com/guide/developing/tools/adb.html – 2010-07-01 20:16:45

回答

0

正如@Cristian Castiblanco說,動態改變視圖導致問題,對於這些場景,您必須創建單獨的活動並使用意向調用它們,並使用捆綁包在它們之間傳遞數據。

+0

你可以幫助修復代碼,這對我來說是一個很大的幫助 – iperetz1 2010-07-03 02:54:40

1

findViewById比人們傾向於認爲它簡單得多。它遍歷視圖層次結構,查找具有給定ID的視圖。如果沒有找到,findViewById返回null。

您首先將內容視圖設置爲main佈局,但後來嘗試findViewById(R.id.backmain)。由於在主佈局中沒有該ID,所以它返回null。那時嘗試other.setOnClickListener將失敗。只有當按鈕實際存在於視圖層次結構中時,才能執行此操作。

動態更改視圖層次結構並沒有什麼內在錯誤,但是如果你走這條路線,你將不得不處理一些不同的事情。 (例如,當您將事件連接到onCreate期間不存在的視圖時,就像上面要做的那樣)。