'[Android] - 개념'에 해당되는 글 27건

  1. 2016.12.04 Layout에 다른 Layout넣기
  2. 2016.11.30 Fragment 기초 예제 1
  3. 2016.11.29 Fragment 기본 개념
  4. 2016.11.25 ViewPage - 2단계
  5. 2016.11.24 ViewPage 기본 개념
  6. 2016.11.24 ViewPager - 1단계
  7. 2016.11.24 Action Bar sample1

* Layout에 다른 Layout넣기 *

 

1. 화면 전체에 나타낼 Layout을 메모리 상에 객체화할 때는 setContentView()를 사용한다.

2. 화면 일부만 별로 Layout을 메모리 상에 객체화 하려면 별도 인플레이션 객체를 사용해야 된다.

   안드로이드에서는 LayoutInflater 클래스를 이용한다.

   이 클래스는 시스템 서비스로 제공되므로 getsystemService(Context.LAYOUT_INFLATER_SERVICE) 메소드를 사용하여

   객체를 참조한 후 사용해야 한다.

 

3. 아래 소스중 activity_main.xml 에서 보면 ["@+id/contentsLayout"] id인 LinearLayout에 위치에 별도 Layout을 넣게 된다.

 

 

[ activity_main.xml ]

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:gravity="center_horizontal"
        android:text="아래 버튼을 누르면 인플레이션으로 추가합니다."
        android:textSize="14dp"
        android:textColor="#ffad6535" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="인플레이션으로 추가하기"
        android:textSize="22dp"
        android:onClick="onButton1Clicked" />

    <LinearLayout
        android:id="@+id/contentsLayout"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
    </LinearLayout>

</LinearLayout>

 

[ button.xml ]

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/selectButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="선택 "
        android:textSize="24dp"
        android:textStyle="bold"
        />
    <RadioGroup
        android:id="@+id/radioGroup01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        >
        <RadioButton
            android:id="@+id/radio01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="남성"
            android:textColor="#ffaaff10"
            android:textStyle="bold"
            android:textSize="24dp"
            />
        <RadioButton
            android:id="@+id/radio02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="여성"
            android:textColor="#ffaaff10"
            android:textStyle="bold"
            android:textSize="24dp"
            />
    </RadioGroup>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical|center_horizontal"
        android:paddingTop="10dp"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="하루종일"
            android:textSize="24dp"
            android:paddingRight="10dp"
            android:textColor="#ffaaff10"
            />
        <CheckBox
            android:id="@+id/allDay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </LinearLayout>
</LinearLayout

 

 

[ MainActivity.java ]

/**
* 레이아웃 인플레이터를 이용해 레이아웃의 일부를 동적으로 로딩하는 방법에 대해 알 수 있습니다.
*
* @author Mike
*/
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**
     * 버튼을 눌렀을 때 레이아웃을 동적으로 로딩합니다.
     * @param v
     */
    public void onButton1Clicked(View v) {
        inflateLayout();
    }

    /**
     * button.xml 에 정의된 레이아웃을 메인 액티비티의 레이아웃 일부로 추가하는 메소드 정의
     */
    private void inflateLayout() {
        // XML 레이아웃에 정의된 contentsLayout 객체 참조
        LinearLayout contentsLayout = (LinearLayout) findViewById(R.id.contentsLayout);

        // 인플레이션 수행
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        // inflate()메소드의 파라미터로 R.layout.button과 contentsLayout객체를 전달하고 앋.

        //이것은 contentsLayout을 부모 컨테이너로 하여 buttons.xml파일에 정의된 레이아우승ㄹ 추가하라는 의미이다.

        inflater.inflate(R.layout.button, contentsLayout, true);

        // 새로 추가한 레이아웃 안에 들어있는 버튼 객체 참조
        Button btnSelect = (Button) findViewById(R.id.selectButton);
        final CheckBox allDay = (CheckBox) findViewById(R.id.allDay);

        btnSelect.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (allDay.isChecked()) {
                    allDay.setChecked(false);
                } else {
                    allDay.setChecked(true);
                }
            }
        });
    }

 

 

 

 

 

 

 

 

 

 

 

'[Android] - 개념 > Layout' 카테고리의 다른 글

Layout에서 별도 Layout 띄우기  (0) 2016.12.04
Posted by 농부지기
,

참고 URL : http://itpangpang.tistory.com/114

 

 

 

 

public class MainActivity extends AppCompatActivity {

        Button btn_move_page1;
        Button btn_move_page2;
        Button btn_move_page3;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            setup();

            movePage1();
        }
        private void setup()
        {
            btn_move_page1 = (Button) findViewById(R.id.btn_move_page1);
            btn_move_page2 = (Button) findViewById(R.id.btn_move_page2);
            btn_move_page3 = (Button) findViewById(R.id.btn_move_page3);

            btn_move_page1.setOnClickListener(myListener);
            btn_move_page2.setOnClickListener(myListener);
            btn_move_page3.setOnClickListener(myListener);
        }

        View.OnClickListener myListener = new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                btn_move_page1.setSelected(false);
                btn_move_page2.setSelected(false);
                btn_move_page3.setSelected(false);

                switch (view.getId()){
                    case R.id.btn_move_page1:
                        movePage1();
                        break;
                    case R.id.btn_move_page2:
                        movePage2();
                        break;
                    case R.id.btn_move_page3:
                        movePage3();
                        break;
                }
            }
        };



        public void movePage1(){
            Page1 page1 = new Page1();
            //FragmentManager : Activity위(안)에서 Fragment와 Activity의 상호작용을 관리
            FragmentManager fragmentManager = getFragmentManager();

            //FragmentTransaction
            //  - 실질적으로 이 Transaction이  Activity위에 Fragment를 올려주고(add) 있던걸 빼고
            //    다시올리고(replace)  제거해주고(remove)  commit등 여러가지 중요한  활동이 가능하게 도와준다.
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.ll_page, page1);
            fragmentTransaction.commit();
        }

        public void movePage2(){
            Page2 page2 = new Page2();
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.ll_page, page2);
            fragmentTransaction.commit();
        }

        public void movePage3(){
            Page3 page3 = new Page3();
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.ll_page, page3);
            fragmentTransaction.commit();
        }

        //버튼 하단에 있는 LinearLayout에 보여줄 페이지 처리
        // - 이때 Activity라면 AppCompatActivity 를 extends 받아야 된다.
        // - extends를 Fragment로 하면서 Activity가 아니라 Fragment임을 알 수 있다.
        //   또한 onCreate()메소드가 아닌 onCreateView()메소드를 이용했다.
        public static class Page1 extends Fragment {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                //화면을 가져오기 위해서 LayoutInflater 객체를 이용했다.
                //  - inflate() : xml을 실제 객체로 사용가능하게 하는 역할을 담당
                View view = inflater.inflate(R.layout.fragment_page1, container, false);
                return view;
            }
        }
        public static class Page2 extends Fragment {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                View view = inflater.inflate(R.layout.fragment_page2, container, false);
                return view;
            }
        }
        public static class Page3 extends Fragment {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                View view = inflater.inflate(R.layout.fragment_page3, container, false);
                return view;
            }
        }

}

 

 

 

'[Android] - 개념 > Fragment' 카테고리의 다른 글

Fragment 기초 예제 3  (0) 2016.12.04
Fragment 기초 예제 2  (2) 2016.12.04
Fragment 기본 개념  (0) 2016.11.29
Posted by 농부지기
,

[ Fragment ]

 

1. 기본 개념

   1. Fragment도 Activity처럼 생명주기가 있지만 Activity위에서 동작하기 때문에 Activity가 종료되면 모든 Fragment도 종료된다.

   2. Fragment는 app.Fragment와 support.v4.app.Fragment library 가 존재

   3. 화면(Activity)를 여러 조각으로 나누워도  관리 및 조회하고 싶을때 Fragment를 사용.

   4. Fragment는 항상 Activity위에 올라가 있어야 한다.

   5. [탭]버튼을 클릭시 다른 화면을 보여줄때 Activity도 가능 하지만 Fragment를 사용하면 더 좋다.

 

   9. 하나의 액티비티 위에 여러 개의 액티비티를 올릴수 있다.

       - 구체적으로 Activity클래스와 AcitivityGroup클래스를 이요하면 구현 가능

       - 하지만 하나의 화면을 독립적으로 구성할 때 필요한 여러 가지 속성들을 사용하면, 안드로이드 시스템에서 관리하는

         애플리케이션 구성 요소이므로 액티비티 안에 다른 액티비티를 넣는 것은 단말의 리소스를 많이 사용하는 비효율적인 방법이 된다.

 

2. Fragment 주요 메소드

   - public final Activity getActivity()

         : 이 프래그먼트를 포함하는 액티비티를 리턴함.

   - public final FragmentManager getFragmentManager()

         : 이 프래그먼트를 포함하는 액티비티에서 프래그먼트 객체들과 의사소통하는 프래그먼트 매니저를 리턴함.  

   - public final Fragment getParentFragment()

         : 이 프래그먼트를 포함하는 부모가 프래그먼트일 경우 리턴함. 액티비티이면 null을 리턴함.

   - public final int getId()

         : 이 프래그먼트의 ID를 리턴함.

 

3. FragmentManager 주요 메소드

   - public abstract FramgentTransaction beginTransaction()

          : 프래그먼트를 변경하기 위한 트랜젝션을 시작함

   - public abstract Framgent  findFragmentById(int id)

          : ID를 이용해 프래그먼트 객체를 찾음

   - public abstract Framgent  findFragmentByTag(String tag)

          : 태그 정보를 이용해 프래그먼트 객체를 찾음

   - public abstract boolean executePendingTransaction()

          : 트랜젝션은 commit()메소드를 호출하면 실행되지만 비동기(asynchronous)방식으로 실행되므로 즉시 실행하고 싶다면 이 메소드를 추가로 호출해야 됨

 

URL : http://itpangpang.tistory.com/''

'[Android] - 개념 > Fragment' 카테고리의 다른 글

Fragment 기초 예제 3  (0) 2016.12.04
Fragment 기초 예제 2  (2) 2016.12.04
Fragment 기초 예제 1  (0) 2016.11.30
Posted by 농부지기
,

참고 url : http://itpangpang.tistory.com/286

* 개발 방향 및 Logic

1. ActionBar를 사용하지 않는다.

2. ActionBar대신에 TextView를 통해서 ActionBar역할을 하도록 한다.

3. ViewPage이동시 swipe기능도 추가한다.

 

[drawable]-[tab_color_selector.xml]

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#301500" android:state_selected="true" />
    <item android:color="#8C8C8C" />
</selector>

 

[drawable]-[tab_bg_off.xml]

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape android:shape="rectangle">
            <padding
                android:bottom="2dp"
                />
            <solid android:color="#8C8C8C" />
        </shape>
    </item>

    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#EAEAEA" />
        </shape>
    </item>
</layer-list>

 

[drawable]-[tab_bg_on.xml]

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape android:shape="rectangle">
            <padding
                android:bottom="5dp"
                />
            <solid android:color="#301500" />
        </shape>
    </item>

    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#EAEAEA" />
        </shape>
    </item>
</layer-list>

 

[drawable]-[tab_bg_selector.xml]

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_selected="false"
        android:drawable="@drawable/tab_bg_off" />
    <item
        android:state_selected="true"
        android:drawable="@drawable/tab_bg_on" />
</selector>

 

 

[FirstFragment.java]  >>  [SecondFragment.java],   [ThirdFragment.java] 두 개 java도 생성

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="30dp"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        android:text="첫번째 페이지"/>

</RelativeLayout>

 

[fragment_first.xml] >> [fragment_second.xml], [fragment_third.xml]  2개도 생성

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="30dp"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        android:text="첫번째 페이지"/>

</RelativeLayout> 

 

 

[ activity_main.xml ]

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/tab_first"
            android:layout_width="0dip"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="@drawable/tab_color_selector"
            android:background="@drawable/tab_bg_selector"
            android:text="친구" />

        <TextView
            android:id="@+id/tab_second"
            android:layout_width="0dip"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="@drawable/tab_color_selector"
            android:background="@drawable/tab_bg_selector"
            android:text="채팅방" />

        <TextView
            android:id="@+id/tab_third"
            android:layout_width="0dip"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="@drawable/tab_color_selector"
            android:background="@drawable/tab_bg_selector"
            android:text="설정" />
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/ll">
    </android.support.v4.view.ViewPager>

</RelativeLayout>

 

 

[ MainActivity.xml ]

package org.example.farmkim.study001;

import android.os.Bundle;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
{
    ViewPager vp;
    LinearLayout ll;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        vp = (ViewPager)findViewById(R.id.vp);
        ll = (LinearLayout)findViewById(R.id.ll);

        //ActionBar 역할을 TextView
        TextView tab_first = (TextView)findViewById(R.id.tab_first);
        TextView tab_second = (TextView)findViewById(R.id.tab_second);
        TextView tab_third = (TextView)findViewById(R.id.tab_third);

        //ViewPage객체에 Adapter 연결
        //이때, ViewPage에 Fragment가 연동된다.
        vp.setAdapter(new pagerAdapter(getSupportFragmentManager()));
        vp.setCurrentItem(0);

        //tab에 OnClick Event설정 및 Tag 값 지정
        tab_first.setOnClickListener(movePageListener);
        tab_first.setTag(0);
        tab_second.setOnClickListener(movePageListener);
        tab_second.setTag(1);
        tab_third.setOnClickListener(movePageListener);
        tab_third.setTag(2);

        tab_first.setSelected(true);

        //ViewPage에  Page가 변경될때 호출되는 Event 추가.
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
        {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
            {

            }

            @Override
            public void onPageSelected(int position)
            {
                int i = 0;
                while(i<3)
                {
                    if(position==i)
                    {
                        ll.findViewWithTag(i).setSelected(true);
                    }
                    else
                    {
                        ll.findViewWithTag(i).setSelected(false);
                    }
                    i++;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state)
            {

            }
        });
    }

    //Tab역할을 하는 상단 TextView를 클릭 시 Event
    View.OnClickListener movePageListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            int tag = (int) v.getTag();

            int i = 0;
            while(i<3)
            {
                if(tag==i)
                {
                    //특정 Component를 선택해준다.
                    //그럴경우, drawable안에  xml에 <selector>tag안에  state_selected="true" 속성을 찾아서 style을 적용한다.
                    ll.findViewWithTag(i).setSelected(true);
                }
                else
                {
                    ll.findViewWithTag(i).setSelected(false);
                }
                i++;
            }

            vp.setCurrentItem(tag);
        }
    };

    //ViewPager객체에 Adapter 연결.
    private class pagerAdapter extends FragmentStatePagerAdapter
    {
        public pagerAdapter(android.support.v4.app.FragmentManager fm)
        {
            super(fm);
        }
        @Override
        public android.support.v4.app.Fragment getItem(int position)
        {
            switch(position)
            {
                case 0:
                    return new FirstFragment();
                case 1:
                    return new SecondFragment();
                case 2:
                    return new ThirdFragment();
                default:
                    return null;
            }
        }
        @Override
        public int getCount()
        {
            return 3;
        }
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'[Android] - 개념 > ViewPage 다루기' 카테고리의 다른 글

ViewPage 기본 개념  (0) 2016.11.24
ViewPager - 1단계  (0) 2016.11.24
Posted by 농부지기
,

1. ViewPage에서 기본 디폴티는 현재 보이는 페이지 좌우만 생성해놓고 사용하는 구조임

    - 그럼 모든 탭의 화면을 항상 유지하고 싶다면  setOffscreenPageLimit를 사용하면 됨

    - 유지라는 뜻은 화면에 사용자가 어떤 값을 입력 시 계속 메모리에 남아 있다는 뜻.

      반데로, 유지하지 못하면 탭이 이동시 사용자가 입력한 값이 사라짐.

 

2. setOffscreenPageLimit()

   - 좌우 몇개의 페이지를 그려놓고(준비)있을지 설정해줌.

   - setOffscreenPageLimit(2) : 좌2, 현재, 우2 와 로 총 5페이지가 그려져(준비)있는 상태

   - http://itpangpang.tistory.com/287

 

3. setUserVisibleHint

   - 첫번째 page에서 두번째 page에 값을 넘기고 싶을 경우 사용

   - http://itpangpang.tistory.com/288

   - 사용방법 :

 

      @Override
      public void setUserVisibleHint(boolean inVisibleToUser){
          if (inVisibleToUser){
              //사용자에게 page가 보일 때 실행할 문장
             count = ((MainActivity)getActivity()).tempCount;  //다른page에서 값을 받을 수 있음.

          }else{
              //사용자에게 page가 안보일 때 실행할 문자d
          }
      }

 

    - 참고. 위에서 tempCount값을 얻어 올려면

              tab을 변경 시 아래와 같은 script가 존재 해야 됨

           ((MainActivity)getActivity()).tempCount = Integer.parseInt(et.getText().toString());

'[Android] - 개념 > ViewPage 다루기' 카테고리의 다른 글

ViewPage - 2단계  (0) 2016.11.25
ViewPager - 1단계  (0) 2016.11.24
Posted by 농부지기
,

참고URL : http://itpangpang.tistory.com/284

 

 [ ViewPager 1단계  ]

* 개발 방향 및 Logic

1. ActionBar를 사용하지 않는다.

2. ActionBar대신에 TextView를 통해서 ActionBar역할을 하도록 한다.

3. TextView (탭버튼)를 클릭 시 ViewPager에 페이지가 변경되도록 한다.

 

 

[activity_main.xml]

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_first"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="첫번째 탭" />

        <Button
            android:id="@+id/btn_second"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="두번째 탭" />

        <Button
            android:id="@+id/btn_third"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="세번째 탭" />
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/ll">
    </android.support.v4.view.ViewPager>

</RelativeLayout>

 

[fragment_first.xml],  [fragment_second.xml], [fragment_third.xml] 3가지 거의 유사

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="30dp"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        android:text="첫번째 페이지"/>

</RelativeLayout>

 

 

[FirstFragment.java], [SecondFragment.java], [ThirdFragment.java]

public class FirstFragment extends Fragment
{
    public FirstFragment()
    {
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.fragment_first, container, false);
        return layout;
    }
}

 

[MainActivity.java]

public class MainActivity extends AppCompatActivity
{
    ViewPager vp;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        vp = (ViewPager)findViewById(R.id.vp);
        Button btn_first = (Button)findViewById(R.id.btn_first);
        Button btn_second = (Button)findViewById(R.id.btn_second);
        Button btn_third = (Button)findViewById(R.id.btn_third);

        //ViewPage의 Page를 관리해주는 Adapter가 필요.
        //ViewPage와 Adapter연결
        vp.setAdapter(new pagerAdapter(getSupportFragmentManager()));

        //ViewPage.setCurrentItem()는 해당 ViewPage에 Fragment 를 보여준다.
        //맨 처음에 setCurrentItem()을 안하면 default로 첫번째(0) Fragment를 보여준다.
        //vp.setCurrentItem(0);

        btn_first.setOnClickListener(movePageListener);
        btn_first.setTag(0);
        btn_second.setOnClickListener(movePageListener);
        btn_second.setTag(1);
        btn_third.setOnClickListener(movePageListener);
        btn_third.setTag(2);
    }

    View.OnClickListener movePageListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            int tag = (int) v.getTag();
            vp.setCurrentItem(tag);
        }
    };

    private class pagerAdapter extends FragmentStatePagerAdapter
    {
        public pagerAdapter(android.support.v4.app.FragmentManager fm)
        {
            super(fm);
        }
        @Override
        public android.support.v4.app.Fragment getItem(int position)
        {
            switch(position)
            {
                case 0:
                    return new FirstFragment();
                case 1:
                    return new SecondFragment();
                case 2:
                    return new ThirdFragment();
                default:
                    return null;
            }
        }
        @Override
        public int getCount()
        {
            return 3;
        }
    }
}

 

'[Android] - 개념 > ViewPage 다루기' 카테고리의 다른 글

ViewPage - 2단계  (0) 2016.11.25
ViewPage 기본 개념  (0) 2016.11.24
Posted by 농부지기
,

 

 

[build.gradle]
아래 내용 추가

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:24.0.0'
}

 

 

 

 

[styles.xml]

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

 

 

 

 

 

[tab_fragment_1.xml]  2~3도 생성 필요

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="This is Tab 1111"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>

 

 

 

 

[activity_main.xml]

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


    <!--Custom Toolbar-->
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />


    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />


    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


</LinearLayout>

 

 

 

 

[TabFragment1 ~ 3]
- 아래는 1만 존재 2,3을 생성해서 하면 됨

package org.example.farmkim.tabbase02;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * Created by Junyoung on 2016-06-23.
 */


public class TabFragment1 extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tab_fragment_1, container, false);
    }
}

 

 

 

 

 

[MainActivity]

package org.example.farmkim.tabbase02;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //-----------------------------------------------------------
        // Adding Toolbar to the activity
        //-----------------------------------------------------------
        // 아래 두 문장이 있어야 상단 toolbar 영역에 title이 조회 됨
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("farmer Toolbar"); //Toolbar title명
        toolbar.setTitleTextColor(Color.BLUE); //타이틀 글자 색
        toolbar.setSubtitle("난 sub title");  //타이틀 아래 작은 글씨로 부제목 표시
        toolbar.setSubtitleTextColor(Color.MAGENTA);  //부제목의 글자색
        toolbar.setNavigationIcon(R.mipmap.ic_launcher); //좌측에 메뉴(네비게이션)아리콘 설정
        setSupportActionBar(toolbar);

        //-----------------------------------------------------------
        // Tab 추가
        // Initializing the TabLayout
        //-----------------------------------------------------------
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.addTab(tabLayout.newTab().setText("Tab One"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab Two"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab Three"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        //-----------------------------------------------------------
        // Initializing ViewPager
        //-----------------------------------------------------------
        viewPager = (ViewPager) findViewById(R.id.pager);

        // Creating TabPagerAdapter adapter
        TabPagerAdapter pagerAdapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());

        // 이때 첫번째 tab에 대한 page가 조회 됨
        // viewPager.setAdapter() : 메소드는 ViewPager에 pagerAdapter를 연결시켜준다.
        // 질문 : 그런데, 맨 처음 왜 첫번째페이지가 조회 되는지 모르겠음 ????
        viewPager.setAdapter(pagerAdapter);

        // 주석 처리 해도 현재 플젝에서는 정상작동
        // addOnTabSelectedListener()가 먼저 수행되고 addOnPageChangeListener()가 수행 됨
        // 상세설명 : http://itpangpang.tistory.com/290
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)
        {
            /*
            스크롤 효과가 나는 동안 계속해서  호출되는 부분이다
            position(0) = 첫번째 탭이었다가
            position(1) = 두번째 탭으로 이동되는 순간1로 변한다.
             */
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
            {
                Log.d("ITPANGPANG","onPageScrolled : "+position);
            }

            /*
              이 놈은 포지션(페이지 위치)과는 전혀 상관이 없다.
              위의 로그찍은걸 보면 매개변수값으로 state값을 받는다.
              그냥 페이지의 상태자체입다.
              state는(0,1,2) 총 3가지 값이 존재합니다.
                  0 : SCROLL_STATE_IDLE
                  1 : SCROLL_STATE_DRAGGING
                  2 : SCROLL_STATE_SETTLING

                  IDLE = 뜻은 가동되지 않은(즉 종료시점이라고 볼 수 있다.)
                  DRAGGING = 뜻 그대로 드래그 되고 있다(Swipe 될 때 호출됩니다. 조금 있다가 확인)
                  SETTLING = 뜻은 고정(정해졌다)이라는 뜻

              사용자가 Swipe로 화면을 끄는것이 아니라서 1(DRAGGING)은 찍히지 않는다.
              0 -> 2 : 두번째 탭을 누르는 순간 탭은 확실히 2번째라고 결정났으니
              (0을) 먼저 찍어주고 그 다음 가동이 종료되면 (남은 페이지 넘어가는효과(스크롤되는중)가 없는 순간) 2번을 찍어준다.
             */
            @Override
            public void onPageScrollStateChanged(int state)
            {
                Log.d("ITPANGPANG","onPageScrollStateChanged : "+state);
            }

            /*
            역시나 Log찍은 코드를 보면  매개변수로 position을 받는다.
            즉, 선택된 페이지를 알려준다.
            Log를 보면 onPageScrollStateChanged : 2  -> 바로 다음에 onPageSelected : 1  가 찍힌 것을 확인 할 수 있다.
            onPageSelected는 ScrollStateChanged = 2라고 결정난 후에야 호출된다.
            2라는 뜻이 무조건 그 페이지가 선택되었다
            고정(정해졌다)이라는 뜻이므로 그때서야 포지션에 맞게 로그를 찍어주는 것이다.
            (단 Swipe가 아닌 선택으로 넘겼을때)
             */
            @Override
            public void onPageSelected(int position)
            {
                Log.d("ITPANGPANG","onPageSelected : "+position);

            }
        });

        // Set TabSelectedListener
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            //새로운 tab을 클릭 시 호출 됨
            //이때 ViewPager에 새로운 페이지를 보여줌.
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.d("ITPANGPANG","---onTabSelected : "+tab.getPosition());
                //Toast.makeText(getApplicationContext(), "onTabSelected  11 ", Toast.LENGTH_SHORT).show();
                viewPager.setCurrentItem(tab.getPosition());
            }

            //다른 tab을 클릭 시 호출 됨 (신규 tab에 대한  onTabSelected()메소드 호출 전에  아래 메소드가 먼저 호출 됨)
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                //Toast.makeText(getApplicationContext(), "onTabUnselected  22", Toast.LENGTH_SHORT).show();
                Log.d("ITPANGPANG","---onTabUnselected : "+tab.getPosition());
            }

            //현재 활성화 되어 있는 tab을 클릭 시 호출
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //Toast.makeText(getApplicationContext(), "onTabReselected 33", Toast.LENGTH_SHORT).show();
                Log.d("ITPANGPANG","---onTabReselected : "+tab.getPosition());
            }
        });
    }

    public static class TabPagerAdapter extends FragmentStatePagerAdapter {
        // Count number of tabs
        private int tabCount;

        public TabPagerAdapter(FragmentManager fm, int tabCount) {
            super(fm);
            this.tabCount = tabCount;
        }

        @Override
        public Fragment getItem(int position) {
            // Returning the current tabs
            // - tab 갯수 만큼 case문장도 동일해야 됨.  그렇지 않으면 [viewPager.setAdapter(pagerAdapter);]에서 오류 발생
            //   case비교값도 0,1,2,3... 와 같이 순차적이여야 함.
            // - 느낌이 [viewPager.setAdapter(pagerAdapter);]할때 getItem()메소드를 tabCount만큼 수행하는거 같음
            //   즉, Fragment 를 모두 만들어 놓음
            //   그런후, onTabSelected(TabLayout.Tab tab)  -> viewPager.setCurrentItem(tab.getPosition())를 하게 되면  화면이 변경 됨
            switch (position) {
                case 0:
                    TabFragment1 tabFragment1 = new TabFragment1();
                    return tabFragment1;
                case 1:
                    TabFragment2 tabFragment2 = new TabFragment2();
                    return tabFragment2;
                case 2:
                    TabFragment3 tabFragment3 = new TabFragment3();
                    return tabFragment3;
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return tabCount;
        }
    }
}


 

Posted by 농부지기
,