2015-02-07 2 views
0

빈 프로젝트를 시작하고 아래에 추가하여 onCreate를 수정했지만 디자인보기에서 볼 수 없어 버튼이 생성되지 않았습니다. 내가 뭘 잘못했는지, 나는 그 텍스트가 표시된 단추를 볼 것으로 예상했다.Android Studio onCreate setContentView

Button b = new Button(this); 
b.setText("Hello Button"); 
setContentView(b); 

+0

당신은 장치 또는 에뮬레이터에서 프로젝트를 실행 했습니까? AFAIK 디자인 뷰는 XML 기반 레이아웃 용입니다. –

답변

0

당신이 코드를 통해 레이아웃을 생성하기 때문에 많은 들으, 당신은 XML 뷰에 표시되지 않습니다. 앱을 만들고 실행하면 Button이 표시되어야합니다. 당신이 오히려 XML 뷰에서 Button를 참조 할 경우

, 당신은 다음과 같이 할 수 main_layout.xml을 수정해야합니다 :

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <Button 
     android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="I am a Button"/> 

</LinearLayout> 

당신은 사용하여 자바 코드에서이 Button에 대한 참조를 얻을 수 있습니다 후 코드 다음 호출 된 setContentView() :

Button button = (Button) findViewById(R.id.button);