2010-07-01 3 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오류 "안드로이드 (프로젝트 이름)이 예상치 않게 중지되었습니다

<?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

+0

어디서 올바르게 할 수 있는지 알려주세요. – iperetz1

+0

logcat을 사용하면 일반적으로 이러한 종류의 오류를 해결하는 데 도움이됩니다. http://developer.android.com/guide/developing/tools/adb.html –

답변

0

@Cristian Castiblanco는 원인이되는 뷰를 동적으로 변경 말했듯 이러한 종류의 시나리오에서는 별도의 액티비티를 만들고 인 텐트를 사용하여 호출하고 번들을 사용하여 데이터를 전달해야합니다.

+0

당신이 코드를 수정하는 데 도움을 주실 수 있으시면 저에게 큰 도움이 될 것입니다. – iperetz1

1

findViewById은 사람들이 생각하는 것보다 훨씬 간단합니다. 주어진 ID로 뷰를 찾는 뷰 계층 구조를 탐색합니다. 발견되지 않으면 findViewById은 null을 반환합니다.

콘텐트 뷰를 main 레이아웃으로 설정했지만 나중에 findViewById(R.id.backmain)을 시도했습니다. 메인 레이아웃에는 ID가있는 뷰가 없기 때문에 null을 반환합니다. 이 시점에서 other.setOnClickListener을 시도하면 실패합니다. 뷰 계층에 버튼이 실제로있는 경우에만이 작업을 수행 할 수 있습니다.

동적으로보기 계층 구조를 변경하는 데는 본질적으로 잘못된 것이 없지만 해당 경로를 탐색 할 경우 다르게 처리해야합니다. (예 : 위의 작업을 수행하려는 것처럼 onCreate 중에 존재하지 않는보기에 이벤트를 연결하는 경우)

관련 문제