본문 바로가기
TechNical/Android

EditText랑 Button, Toast를 써 보자.

by 강멍멍이 2010. 11. 21.
반응형
버튼을 누르면 에디트텍스트 박스에 글을 찍어주고 토스트도 출력해 보자.

[main.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<EditText
    android:layout_width="150px"
    android:layout_height="40px"
    android:id="@+id/et_text"
    android:scrollHorizontally="true"
    />
<Button
 android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Touch"
    android:id="@+id/btn_setText"
    />
</LinearLayout>

scrollHorizontally 얘를 true로 설정하면 글자가 많아져도 자동으로 늘어나거나 개행이 되지 않는다.
기본은 자동으로 늘어나는건데 그걸 원치 않을때도 있으니까 ~
사이즈 강제 지정은 저렇게 px나 기타 단위를 써줘야 한다. 아니면 에러뜸ㅋ

[MyTest.java]
package lovelyocto.MyTest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MyTest extends Activity {
 
   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);              
       
        Button btn_setText = (Button)findViewById(R.id.btn_setText);
       
        btn_setText.setOnClickListener(new Button.OnClickListener(){
   
    public void onClick(View v) {  
     EditText et_Text = (EditText)findViewById(R.id.et_text);
     et_Text.setText("Button Tap");
     Toast.makeText(MyTest.this, "Toast Test", Toast.LENGTH_SHORT).show();
    }
         
         }
        );
    }
}

... 보시다시피 별거없다.
findViewById 할때 타입을 꼭 맞쳐줘야 하더라.. 이클립스가 쿡쿡 찍어 주니까 시키는대로 하자.
노란줄 그어져 있는 걸 의심하자.
문법 에러는 아니지만 앱을 실행시키면 느닷없이 죽는 경우가 있다.
예를 들면
EditText et_Text = (EditText)findViewById(R.id.et_text);
이 녀석을 onCreate 밖으로 빼 버리면 문법 에러는 아니지만

~~응용프로그램(~~프로세스)이 예상치 않게 중지되었습니다. 다시 시도해 주세요.

라는 무시무시한 팝업을 만나게 된다.. ㅡ.ㅡ
DDMS를 봐도 뚜렷하게 뭔가 잡히지는 않는다... 이게 뭔가라고 한참을 고민했다.
uncaught exception 이니... nullpointer exception이니.. 이렇게 있는데
자세히 보면 <init>(MyTest.java:12) 라고 적힌 부분을 발견하게 된다.
초기화때 에러가 나니까 init이라고 찍어 준건가??
아하.. 얘구나~라고 생각을 해야 하는 것인가.. 아직 나도 잘 모르겠다 ㅋㅋㅋㅋㅋㅋㅋㅋㅋ
나 왜 이렇게 허접하니 ㅠ.ㅠ
... 어렵다 -_-

매일매일 조금씩이라도 재미삼아 공부삼아~
반응형

댓글