2011-09-12 3 views
0

레이아웃의 단추에 대한 클릭 수신기를 설정하려고합니다. 나는 팽창 레이아웃에서보기를 찍을 때 나는 findViewById를 호출 할 때 클릭 리스너는 트리거() 아니라 직접 :확장 된 뷰가 클릭 리스너에 응답하지 않는 이유는 무엇입니까?

여기
public class MyActivity extends Activity implements View.OnClickListener { 
    private static final String TAG = "MyActivity"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.test); 

     Button button = (Button)findViewById(R.id.mybutton); 
     button.setOnClickListener(this); 

     LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     ViewGroup rootLayout = (ViewGroup)inflater.inflate(R.layout.test, 
      (ViewGroup)findViewById(R.id.myroot), false); 
     rootLayout.getChildAt(0).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Log.d(TAG, "Click from inflated view"); 
      } 
     }); 
    } 

    @Override 
    public void onClick(View v) { 
     Log.d(TAG, "Click"); 
    } 
} 

내 배치된다

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/myroot" android:orientation="vertical" 
    android:layout_width="fill_parent" android:background="#ffffff" 
    android:layout_height="fill_parent"> 
    <Button android:text="Button" android:id="@+id/mybutton" 
     android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> 
</LinearLayout> 

는 이유는 무엇입니까? 나는 풍선 이벤트가 아닌 첫 번째 메소드에서만 클릭 이벤트를 얻습니다.

답변

1

밖으로 나가면 setContentView(rootLayout)으로 전화해야합니다.

4

클릭 계층 구조에 추가 한 항목을 추가하지 않았기 때문에 첫 번째 방법 (LogCat에 "Click"을 전송하는 방법)에서만 클릭 이벤트가 발생합니다. onCreate() 메서드의 두 번째 줄인 setContentView(R.layout.test);은 레이아웃 파일에서 뷰를 부 풀리고이를 활동의 뷰 계층 구조에 추가합니다. 몇 줄 후에 수동으로 인플레이션을 수행하면 뷰 계층 구조에 rootLayout을 추가하는 것을 잊어 버리게됩니다. 이렇게하지 않으면 클릭 할 것이 없으므로 LogCat에서 다른 onClick() 메소드의 결과가 출력되지 않습니다.

관련 문제