[09-D2][UI 설계] Widget Event, Widget(TextView(레이블), Button), LinearLayout

[01] Widget Event

1. Event Type 1: event를 현재 Activity가 구현한 경우, Activity가 규모가 커지면 로직과 이벤트 등록 및
    처리하는 모듈이 복잡하게 엉킬 수 있음. Activity가 간단할 경우 사용.

public class LinearLayoutTest extends Activity implements OnClickListener{
.....
        btnHor = (Button)findViewById(R.id.btnHor);
        btnHor.setOnClickListener(this); 
.....
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v.getId() == R.id.btnHor){
            lly.setOrientation(LinearLayout.HORIZONTAL);
        }else if(v.getId() == R.id.btnVer){
            lly.setOrientation(LinearLayout.VERTICAL);
        }else if(v.getId() == R.id.btnRight){
            lly.setGravity(Gravity.RIGHT);
        }
    }

 


2. Event Type 2: event를 내부 무명 클래스로 구현한 경우, 이벤트의 패턴이 다양해 switch문등으로 처리하기
    곤란한 경우.

    Listener  인터페이스는 View클래스의 inner interface로 선언되어 있음으로 View.Listener의 형태로 구현
        btnLeft = (Button)findViewById(R.id.btnLeft);
        btnLeft.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                lly.setGravity(Gravity.LEFT);
            }
        });

 

3. Event Type 3: event를 내부 클래스로 구현한 경우, 이벤트의 타입이 비슷하던, 다양하던 사용가능한 형태,
    객체명을 주의해서 지정.

        btnRight = (Button)findViewById(R.id.btnRight);
        btnRight.setOnClickListener(clickLsn);

.....
    Button.OnClickListener clickLsn = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           switch(v.getId()){
           case R.id.btnRight:
               lly.setGravity(Gravity.RIGHT);
               break;
              
           }
        }
    };

 


4. Event Type 4: event를 다른 클래스가  구현한 경우, Activity가 단순해지는 효과가 있으나 이벤트를 구현한 클래스 이름을 전부
다르게 지정해야함으로 이벤트가 많아지면 이름지정에 매우 어려움.

-- 이벤트의 구현
public class BtnClickEvent implements OnClickListener{

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v.getId() == R.id.btnHor){
            lly.setOrientation(LinearLayout.HORIZONTAL);
        }else if(v.getId() == R.id.btnVer){
            lly.setOrientation(LinearLayout.VERTICAL);
        }else if(v.getId() == R.id.btnRight){
            lly.setGravity(Gravity.RIGHT);
        }
    }


-- Activity에서의 사용
        BtnClickEvent btnClickEvent = new btnClickEvent();
        btnHor = (Button)findViewById(R.id.btnHor);
        btnHor.setOnClickListener(btnClickEvent); 

 


[02] Widget(TextView(레이블), Button), LinearLayout

1. TextView(레이블)
   - import android.widget.TextView;
   - 레이블
   - View --> TextView
   - 단순한 문자열의 출력.
   - 출력 문자열은 변경할 수 없다.
   - width, height는 권장하지 않음.

 


2. Button
   - import android.widget.Button;
   - 버튼
   - View --> TextView --> Button
   - TextView를 상속받으며 사용자의 tab 이벤트를 주로 처리한다.

 


3. LinearLayout
   - 직선형의 배치 방식, View를 수평 또는 수직의 라인을 View를 배치,
     입력 양식에 많이 사용된다.
   android:orientation: 뷰가 출력될 방향을 지정한다.
   android:layout_width="fill_parent": 부모의 영역을 전부 사용
   android:layout_height="wrap_content": 필요한 만큼만 사용
   android:gravity: 현재 View안에서 View안의 내용을 어디에 배치할 것인지 지정.
   android:gravity = "center_vertical|right" 처럼 중첩 상용 가능.
   android:layout_gravity: 부모 View안에서 View의 내용을 어디에 배치할 것인지 지정.
   android:layout_weight: 부모 View안에서 View가 차지할 비중을 정의.
   android:baselineAligned: 수평으로 배치되는 View들을 아래쪽 라인을 맞춤.

 

 

[03] 실습

1. 프로젝트 생성
   - Project Type: Android Project
     Project name: LinearLayoutTest_4
     Application name: LinearLayoutTest_4
     Package name: test.linearLayoutTest
     Create Activity(Activity name): LinearLayoutTest
     Min SDK Version: 4
     Device Configurations: 1.6 -- ADP1, 2.1 -- Nexus One 으로 지정

 


2. 문자열 리소스 정의

>>>>> res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">LinearLayoutTest!</string>
    <string name="app_name">LinearLayout 테스트</string>
    <string name="btnHorStr"> 가로 </string>
    <string name="btnVerStr"> 세로 </string>
    <string name="btnLeftStr"> 왼쪽 </string>
    <string name="btnCenterStr"> 가운데 </string>
    <string name="btnRightStr"> 오른쪽 </string>
    <string name="lbl01"> 123 </string>
    <string name="lbl02"> ABC </string>
    <string name="lbl03"> 가나다라마바사 </string>
</resources>

 

3. View 생성 및 배치
   - Layout파일명은 영어 소문자 및 숫자, _만 가능함.
   - OutLine View의 사용

>>>>> res/layout/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"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<LinearLayout android:id="@+id/LinearLayout01"
              android:layout_width="wrap_content" android:layout_height="wrap_content">
    <Button android:id="@+id/btnHor"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="@string/btnHorStr"
            android:textSize="16dp"/>
    <Button android:id="@+id/btnVer"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="@string/btnVerStr"
            android:textSize="16dp"/>
    <Button android:id="@+id/btnLeft"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="@string/btnLeftStr"
            android:textSize="16dp"/>
    <Button android:id="@+id/btnCenter"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="@string/btnCenterStr"
            android:textSize="16dp"/>
    <Button android:id="@+id/btnRight"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="@string/btnRightStr"
            android:textSize="16dp"/>           
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout02"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation = "horizontal">
    <TextView android:id="@+id/txv01"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/lbl01" android:textColor="#FF0000"
              android:textSize="16dp"/>
    <TextView android:id="@+id/txv02"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/lbl02" android:textColor="#00FF00"
              android:textSize="16dp"/>
    <TextView android:id="@+id/txv03"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/lbl03" android:textColor="#0000FF"
              android:textSize="16dp"/>
        
</LinearLayout>
</LinearLayout>

 


4. Class(이벤트) 작성

>>>>> src/test.linearLayoutTest.LinearLayoutTest.java
package test.linearLayoutTest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class LinearLayoutTest extends Activity implements OnClickListener{

    Button btnHor;
    Button btnVer;
    Button btnLeft;
    Button btnCenter;
    Button btnRight;

    LinearLayout lly;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); // main.xml
       
        // Event Type 1
        // event를 현재 Activity가 구현한 경우
        btnHor = (Button)findViewById(R.id.btnHor);
        btnHor.setOnClickListener(this); // 이벤트 등록       
        btnVer = (Button)findViewById(R.id.btnVer);
        btnVer.setOnClickListener(this); // 이벤트 등록
       
        // Event Type 2
        // event를 내부 무명 클래스로 구현한 경우
        // Listener  인터페이스는 View클래스의 inner interface로 선언되어 있음으로
        // View.Listener의 형태로 구현
        btnLeft = (Button)findViewById(R.id.btnLeft);
        btnLeft.setOnClickListener(new Button.OnClickListener(){ // 이벤트 등록
            public void onClick(View v){
                lly.setGravity(Gravity.LEFT);
            }
        });
        btnCenter = (Button)findViewById(R.id.btnCenter);
        btnCenter.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                lly.setGravity(Gravity.CENTER);
            }
        });
       
        // Event Type 3
        // event를 내부 클래스로 구현한 경우
        btnRight = (Button)findViewById(R.id.btnRight);
        btnRight.setOnClickListener(clickLsn);
       
        lly = (LinearLayout)findViewById(R.id.LinearLayout02);
       
    }
   
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v.getId() == R.id.btnHor){
            lly.setOrientation(LinearLayout.HORIZONTAL);  // 수평 정렬
        }else if(v.getId() == R.id.btnVer){
            lly.setOrientation(LinearLayout.VERTICAL);       // 수직 정렬
        }
    }
   
    Button.OnClickListener clickLsn = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           switch(v.getId()){
           case R.id.btnRight:
               lly.setGravity(Gravity.RIGHT);
               break;
              
           }
        }
    };

}

 

 

[03]  Resource를 XML로 분리하지 않고 Application을 구현하는 방법
         - 안드로이드의 버그로 Widget과 Layout이 같이 출력이 되지 않음으로
           메인 레이아웃에 자식 레이아웃을 추가할시 이상 작동 발생할 수 있음.

1. 프로젝트 생성
   - Project Type: Android Project
     Project name: WidgetCreate_4
     Application name: WidgetCreate_4
     Package name: test.widgetcreate
     Create Activity(Activity name): WidgetCreate
     Min SDK Version: 4

 


2. WidgetCreate.java

package test.widgetcreate;

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.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class WidgetCreate extends Activity implements OnClickListener{
    LinearLayout llyMain;  // 메인 레이아웃

    TextView txvSu1;   // 수 1
    EditText edtSu1;    // [     ]
    TextView txvOper;  // +
    TextView txvSu2;   // 수 2
    EditText edtSu2;    // [     ]
   
    Button btnAdd;        // 결과 
    EditText edtResult;  // [     ]
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        llyMain = new LinearLayout(this);
        llyMain.setOrientation(LinearLayout.HORIZONTAL);
        setContentView(llyMain);

        displayUI();   

    }
   
    public void displayUI(){
        // View 생성
        txvSu1 = new TextView(this);   // View 생성
        txvSu1.setText("수1: ");          // 문자열 지정
        txvSu1.setTextSize(16);          // 크기 지정
        txvSu1.setTextColor(Color.rgb(0, 255, 0));  // 색상 지정
        setLLParams(txvSu1);            // layout_height, layout_width 레이아웃 지정
        llyMain.addView(txvSu1);       // 부모 View에 추가
       
        edtSu1 = new EditText(this);
        edtSu1.setWidth(70);
        edtSu1.setTextSize(16);
        setLLParams(edtSu1);
        llyMain.addView(edtSu1);

        txvOper = new TextView(this);
        txvOper.setText(" + ");
        txvOper.setTextSize(16);
        txvOper.setTextColor(Color.rgb(0, 255, 0));
        setLLParams(txvOper);
        llyMain.addView(txvOper);
       
        txvSu2 = new TextView(this);
        txvSu2.setText("수2: ");
        txvSu2.setTextSize(16);
        txvSu2.setTextColor(Color.rgb(0, 255, 0));
        setLLParams(txvSu2);
        llyMain.addView(txvSu2);
       
        edtSu2 = new EditText(this);
        edtSu2.setWidth(70);
        edtSu2.setTextSize(16);       
        setLLParams(edtSu2);
        llyMain.addView(edtSu2);
       
        btnAdd = new Button(this);
        btnAdd.setText("결과");
        btnAdd.setOnClickListener(this);  // 이벤트 등록
        btnAdd.setTextSize(16);
        setLLParams(btnAdd);
        llyMain.addView(btnAdd);
       
       
        edtResult = new EditText(this);
        edtResult.setWidth(100);
        edtResult.setTextSize(16);       
        setLLParams(edtResult);
        llyMain.addView(edtResult);
       
    }
 
    @Override
    public void onClick(View v) {
        if (v == btnAdd){
            int su1 = Integer.parseInt(edtSu1.getText().toString());
            int su2 = Integer.parseInt(edtSu2.getText().toString());
            String str = String.valueOf(su1+su2);  // 문자열 변환
           
            // Toast.makeText(this, str, Toast.LENGTH_SHORT).show();  // 2초
            edtResult.setText(str);
       
        }
   }
   
    //리니어 레이아웃의 파라미터 지정
    private  void setLLParams(View view) {
        view.setLayoutParams(new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));
    }    
}

 

 

 
 

Posted by ▶파이팅◀

블로그 이미지
Let's start carefully from the beginning
▶파이팅◀

태그목록

공지사항

Yesterday
Today
Total

달력

 « |  » 2024.4
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

최근에 올라온 글

최근에 달린 댓글

글 보관함