ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • TableLayout 동적 생성
    안드로이드/학습&강좌 2011. 4. 17. 17:27

    이번에 만들어 볼 것은 아이폰의 Ibooks 와 같은 Ibook 테마의 뷰를 테이블 레이아웃으로 만들어 보도록 하겠습니다.

    최근에 어플을 보면 아이북처럼 책장 형식의 UI가 많이 포함되어 있다는 것을 느낄 수 있습니다.

    최근의 대세라고 봐야 하는건가? ㅎㅎ

    사용자가 원한다면 개발자들을 어쩔 수 없이 따라야 겠지요, 월급은 고객이 주는 것이니까...

    만들어볼 화면 부터 보도록 하겠습니다. 대충의 현재 아이북을 배경으로 했구요, 사용하는 이미지 파일 같은 경우는

    공유하지 않습니다~ ㅎ 저작권이 있을 수도 있으므로?


    갤럭시 Tab에 적용한것이라 화면이 좀 크다;;

    위에 보이는 점 같은 경우는 페이지 표시로 만들어 본 것이고 좌우로 플립이 가능 하도록 설계 하였습니다.

    각 책장의 위치는 대충 조절 한거라 양해를 바라고, 각 행과 열마다의 위치와 간격을 조절 할 수 잇는 파라미터를 두어 컨트롤

    할 수 있게끔 구성 하였습니다~


    우선 각각의 책장에 들어갈 이미지를 Layout을 따로 만들어서 Inflate 하여 그 레이아웃을 불러 오게끔 ~ 그래야 다양한 UI를 마

    음대로 조절 할 수 있을 테니

    일단 이 레이아웃을 정의해 보자면

    table_item.xml


    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:orientation="horizontal">
     <FrameLayout
      android:layout_marginTop="7dip"
      android:layout_marginLeft="20dip"
      android:layout_marginRight="20dip"
      android:layout_width="141px"
      android:layout_height="168px"
      android:duplicateParentState="false"
      android:background="@drawable/book1bg">
      <ImageView
       android:id="@+id/table_store_book"
       android:layout_width="124px"
       android:layout_height="159px"
       android:background="@drawable/bookicon"
       />
      <ImageView
       android:id="@+id/store_book_tag"
       android:layout_width="75px"
       android:layout_height="75px"
       android:layout_gravity="left"
       android:background="@drawable/tac1_sample"
       >
      </ImageView>
     </FrameLayout>
    </LinearLayout>


    프레임으로 책에 들어가는 이미지들은 얼마든지 겹쳐서 표시 할 수 있다. 무엇인들 레이아웃 작업 하는게 아직까진

    안드로이드에서 가장 노가다? 작업이라는 느낌이 많이 든다;;

    테이블 레이아웃을 구성할~ 메인 Layout

    table_layout.xml

    <?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">
      <LinearLayout
       android:id="@+id/TableFrame"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:gravity="center_horizontal"
       android:layout_marginTop="5dip"
       android:background="@drawable/bg_02"
       android:orientation="vertical">
       <!-- 윗부분의 페이지를 나타낼 부분  -->
       <LinearLayout
        android:id="@+id/paging_layout"
        android:gravity="center"
        android:layout_marginTop="5dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
       </LinearLayout>
       <!-- 플리퍼로 화면을 감싼다  -->
       <ViewFlipper
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/flip_table">
        <LinearLayout
         android:orientation="vertical"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:visibility="visible">
         <!-- 테이블 레이아웃을 들어갈 부분  -->
         <TableLayout
          android:id="@+id/store_table"
          android:layout_marginTop="30dip"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent">
         </TableLayout>
        </LinearLayout>
       </ViewFlipper>
      </LinearLayout>
    </LinearLayout>

    화면의 설명은 대충 주석으로 이해 하세요~

    이제 화면구성은 끝났고~ 실제 자바 코드를 보도록 하지요

    Study_TableLayout.java

    package epong.exam;

    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.animation.AnimationUtils;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TableLayout;
    import android.widget.TableRow;
    import android.widget.ViewFlipper;

    public class Study_TableLayout extends Activity implements OnFlipListener {
     TableLayout store_table; // Table
     TableRow tr;   //Table Row
     TableRow.LayoutParams params;  // 간격을 지정할 param

     LayoutInflater inflater; // 인플레이터
     int margin = 55;  // 책들간의 간격
     ImageView image[];

     /**
      * 플리퍼 관련 부분 생략~
     */
     private ViewFlipper m_flpFlipper;
     private float m_fStart;
     private float m_fEnd;
     private boolean m_bChangeScreen = false;

     // 현재 페이지를 나타낼 변수
     int pagecount = 0;
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      super.onCreate(savedInstanceState);
      setContentView(R.layout.table_layout);
      LinearLayout layout = (LinearLayout) findViewById(R.id.paging_layout);
      inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      image = new ImageView[3];
      LinearLayout pagelay = (LinearLayout) findViewById(R.id.paging_layout);
      m_flpFlipper = (ViewFlipper) findViewById(R.id.flip_table);
      setOnFlipListener();
      for (int j = 0; j < 3; j++) {
       image[j] = new ImageView(this);
       layout = (LinearLayout) inflater.inflate(
         R.layout.store_main_paging, null);
       image[j] = (ImageView) layout.findViewById(R.id.pageOn);
       // image.setVisibility(View.VISIBLE);
       image[j].setId(j);
       pagelay.addView(layout);
      }

      

      pageNavication(pagecount);
      store_table = (TableLayout) findViewById(R.id.store_table);

      // int nValue = 6 * page;
      for (int i = 0; i < 3; i++) {
       tr = new TableRow(this);
       for (int j = 0; j < 3; j++) {
        LinearLayout table_item = (LinearLayout) inflater.inflate(
          R.layout.table_item, null);
        ImageView Img_Book = (ImageView) table_item
          .findViewById(R.id.table_store_book);
        
        
        //행마다 책이미지를 변경해 보았습니다. 밋밋 하니깐 ㅎ
        if(i == 1)
        {
         Img_Book.setBackgroundResource(R.drawable.bookicon1);
        }
        else if(i == 2)
        {
         Img_Book.setBackgroundResource(R.drawable.icon3);
        }
        ImageView Img_Tag = (ImageView) table_item
          .findViewById(R.id.store_book_tag);
        params = new TableRow.LayoutParams(
          android.widget.TableRow.LayoutParams.WRAP_CONTENT,
          android.widget.TableRow.LayoutParams.WRAP_CONTENT);

        tr.addView(table_item, params);
        if (i > 0) {
         params.topMargin += margin + 10;
        }
       }
       store_table.addView(tr);
      }

     }

     public void pageNavication(int curPage) {
      for (int i = 0; i < image.length; i++) {
       if (i == curPage) {
        image[i].setVisibility(View.VISIBLE);
       } else {
        image[i].setVisibility(View.INVISIBLE);
       }

      }
     }

     @Override
     public void onFlipLeft() {
      m_flpFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
        R.anim.slide_right_in));
      m_flpFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
        R.anim.slide_right_out));
      m_flpFlipper.showNext();
      pagecount++;
      pageNavication(pagecount);
     }

     @Override
     public void onFlipRight() {
      m_flpFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
        R.anim.push_right_in));
      m_flpFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
        R.anim.push_right_out));
      m_flpFlipper.showPrevious();
      pagecount--;
      pageNavication(pagecount);
     }

     @Override
     public void setOnFlipListener() {
      m_flpFlipper.setOnTouchListener(new View.OnTouchListener() {
       @Override
       public boolean onTouch(View _v, MotionEvent _event) {
        switch (_event.getAction()) {
        case MotionEvent.ACTION_DOWN: {

         m_bChangeScreen = true;
         m_fStart = _event.getX();
        }
         break;
        case MotionEvent.ACTION_MOVE: {
         if (m_bChangeScreen == false) {
          m_fEnd = _event.getX();
          if (m_fStart - _event.getX() < -MOUSE_MOVE_SENSITIVITY) {
           m_fStart = _event.getX();
           onFlipRight();
          } else if (m_fStart - _event.getX() > MOUSE_MOVE_SENSITIVITY) {
           m_fStart = _event.getX();
           onFlipLeft();
          }
         }
        }
         break;

        case MotionEvent.ACTION_UP: {
         m_fEnd = _event.getX();
         if (m_fStart - m_fEnd < -MOUSE_DRAG_SENSITIVITY) {
          onFlipRight();
         } else if (m_fStart - m_fEnd > MOUSE_DRAG_SENSITIVITY) {
          onFlipLeft();
         }
         m_bChangeScreen = false;
        }
         break;
        }
        return true;
       }
      });
     }

    }



    실제로는 필요한 부분의 코드만을 넣고 설명해 드려야 하는데 궁금하신 부분은 질문 해 주세요~

    이것으로~ 완성

    플립을 하게 됐을 때의 화면 같은 경우엔

    01


    이렇게 구성됩니다~

    지금은 고정적으로 배치햇지만 사용자가 구성할 화면의 페이지에 따라 자료를 각기 다르게 셋팅할 수도 있겠지요~

    이제 또 다음강좌는 무엇으로 할지~~ 생각 해 봅니다 ㅎ

    댓글

COPYRIGHT 2010 EpoNg. ALL RIGHTS RESERVED.