이 블로그 검색

2011년 3월 16일 수요일

inflate와 setContentView

Inflate를 시켜서 생성한 View 객체와 그 내부의 View들을 findViewById 로 바로 가져 올 수 없다. 아직 메모리에 올라온 것이 아닌가 보다. (Null pointer Exception)
예를들어,
   LinearLayout testA = (LinearLayout)inflater.inflate(R.layout.XXX, null) 로 인플레잇을 시키고,
   testA 안에 있는 testB라는 레이아웃을
   LinearLayout testB =  (LinearLayout)findViewById(R.id.testB) 라고 해서 찾을 수 없다.

그럼 어떻게 하느냐?
=>
1. setContentView(testA) 를 먼저 호출하고 그 뒤에 써 준다.

2. LinearLayout testB =  (LinearLayout)testA.findViewById(R.id.testB) 라고 써 준다.



* 참고

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 //       setContentView(R.layout.main);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout main =  (LinearLayout)inflater.inflate(R.layout.main, null);

      final LinearLayout inLayout = (LinearLayout)findViewById(R.id.inLayout);   
// --> 에러 난다. Nullpointer Exception.               
     setContentView(main);   // setContentView 가 어디 있느냐에 따라.. 달라진다.
     final LinearLayout inLayout = (LinearLayout)findViewById(R.id.inLayout); 
// 에러 안난다. setContentView 에서 메모리에 올렸기 때문에 찾을 수 있다.   
        Button btn = (Button)findViewById(R.id.aaa);
         // 버튼을 누르면 새 뷰가 추가됨.
        btn.setOnClickListener(new Button.OnClickListener(){
         @Override
   public void onClick(View v) {
          LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          LinearLayout route_info_tab = (LinearLayout) inflater.inflate(R.layout.route_info_tab, null);  // 추가할 녀석
    inLayout.addView(route_info_tab);
   }
        })

댓글 없음:

댓글 쓰기