2011-03-09 9 views
1
import android.app.Activity; 
import android.os.Bundle; 
import android.widget.TextView; 
import android.widget.Toast; 

public class ViewId extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     TextView txtArea = new TextView(this); 
     txtArea.setId(20); 
     txtArea.setText("Hello"); 

     TextView view = new TextView(this); 
     view = (TextView) this.findViewById(20); 
     Toast.makeText(this,view.getText(), Toast.LENGTH_LONG).show(); 
    } 
} 

위의 코드를 Eclipse에서 디버깅 할 때 뷰의 값이 변수 창에 null로 표시됩니다. 무엇이 문제입니까? 또는 textview의 setid 및 XML 파일을 사용하지 않고 해당 특정 ID에서 해당 텍스트보기를 retrive 다른 메서드가 있습니다.findviewbyid가 android에서 작동하지 않습니다.

+3

http://developer.android.com/resources/tutorials/hello-world.html에 시간을 할애해야한다고 생각합니다. – ingsaurabh

답변

5

코드가 약간 지저분합니다. 먼저 사용하지 않는 xml 레이아웃으로 contentview를 설정합니다. 또한 TextView txtArea를 만들고 id를 20으로 설정합니다.이 뷰는 내용에 추가하지 않으므로 나중에 찾을 수 있습니다.

다음을 결정해야합니다. 레이아웃을 XML로 작성하여 사용하십시오. 또한 프로그래밍 방식으로 수정하거나 프로그래밍 방식으로 자신 만의 레이아웃을 만들고 내용보기를 새로 만든 레이아웃 /보기로 설정할 수 있습니다.

+0

콘텐츠에 textview를 넣지 않으면 앱이 어떻게 검색되는지 절대 알 수 없습니다. . 그러나 하나 더 질문. 만약 내가 tablayout-> tablerow-> textview dinamically 다음 findViewbyid 작동하지 않거나 내 코드를 변경해야 textview 넣어? – Nirav

+0

콘텐츠에있는 한 작동해야하지만 ... 동적으로 만들면 인스턴스를 멤버 변수로 유지하면 findViewById()를 호출 할 필요가 없습니다. 그것에 대한 참조를 .... – WarrenFaith

관련 문제