Android/2012.04월 강좌
2일차 이벤트2
Bohemian life
2012. 4. 27. 17:26
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:id="@+id/layout"> <!-- id가 있으면 findViewById()가 가능해진다. --> <TextView android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="누르세요"/> <Button android:id="@+id/button2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="누르세요"/> </LinearLayout>
package com.gusfree; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class EventListenerActivity extends Activity { int i=1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.main);//main.xml을 화면으로! //1번 버튼을 누르면 a 실행해라 버튼을 찾자 //2번 버튼을 누르면 b 실행해라 //UpCasting 발생 View view =this.findViewById(R.id.button1); //다운 캐스팅 시키자 //xxx를 찾아라. xxx를 찾았다. 남자xxx; Button btn1 =(Button)view; final TextView tv=//메서드 안에 있는 지역 변수 (TextView) this.findViewById(R.id.textView1); final LinearLayout layout= (LinearLayout)findViewById(R.id.layout);//LinearLayout을 찾는다 //버튼 누르면 실행될 메서드 연결 //set + OnClickListener btn1.setText("버튼1"); btn1.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { //버튼1을 클릭하면 이쪽으로 제어 이동 if(i<10){ i++; tv.setText("버튼1을 " +i +"번 눌렀다."); }else{ tv.setText(i+"그만눌러라"); } //0.00000~1.00000 까지의 실수를 아무거나 리턴 double x =Math.random(); int red =(int)(x*255); tv.setBackgroundColor(Color.RED); layout.setBackgroundColor( Color.rgb(red,50,70));//0~255 } }); //2번 버튼 누르면 "2번 버튼 눌렀다." 표시하기 final Button btn2 = (Button) this.findViewById(R.id.button2); btn2.setText("버튼2"); btn2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { i--; tv.setText("버튼2을 " +i+"번 눌렀다."); tv.setBackgroundColor(Color.YELLOW); layout.setBackgroundColor(Color.RED); } }); } }