'2016/12'에 해당되는 글 10건

  1. 2016.12.07 ListView 정의
  2. 2016.12.06 ListView 기초예제1
  3. 2016.12.04 Fragment 기초 예제 3
  4. 2016.12.04 Fragment 기초 예제 2 2
  5. 2016.12.04 AlertDialog
  6. 2016.12.04 Toast
  7. 2016.12.04 Intent() 정의
  8. 2016.12.04 Intent를 이용해 Layout 띄우기
  9. 2016.12.04 Layout에서 별도 Layout 띄우기
  10. 2016.12.04 Layout에 다른 Layout넣기

[ ListView 정의 ]

 

1. 정의

    1. 안드로이드에서는 ListView처럼 여러 개의 아이템 중에 하나를 선택할 수 있는 위젯들을 '선택위젯'이라고 한다.

    2. 선택할 수 있는 여러 개의 아이템이 표시되는 선택위젯은 어댑터(Adapter)를 통해 각각의 아이템을 화면에 디스플레이한다.

        따라서 원본 데이터는 어댑터에 설정해야 하며 어탭터가 데이터 관리 기능을 담당한다.

        선택 위젯에 보이는 각각의 아이템이 화면에 디스플레이되기 전에 어탭터의 getView()메소드가 호출 된다.

 

2. 선택 위젯

    1. 일반 위젯들은 직접 위젯에 데이터를 설정할 수 있다. 

    2. 선택 위젯은 직접 위젯에 접근하여 데이터를 설정할 수 없다.

    3. 그래서 어댑터(Adapter)패턴을 사용하여, 어댑터에서 만들어주는 뷰를 이용해 리스트뷰의 한 아이템으로 보여주는 방식을 사용한다.

    4. 대표적인 선택위젯 : 리스트뷰/스피너/그리드 뷰/갤러리

 

3. getView()

   1.  이 메소드는 어탭터에서 가장 중요한 메소드로 이 메소드에서 리턴하는 뷰가 하나의 아이템으로 호출 된다.

   - Reference

       public View getView(int position, View converView, ViewGroup parent)

   

    1. position : 아이템의 인덱스를 의미

                       리스트 뷰에서 보일 아이템의 위치 정보이다.

                       0 부터 시작하여 아이템의 개수만큼 파라미터로 전달 된다.

    2. converView : 현재 인덱스에 해당되는 뷰 객체를 의미

                             안드로이드에서는 선택 위젯이 데이터가 많아 스크롤될 때 뷰를 재 활용하는 메커니즘을 가지고 있어

                             한 번 만들어진 뷰가 화면 상에 그대로 다시 보일 수 있도록 되어 있다.

                             (이미 만들어진 뷰들을 그대로 사용하면서 데이터만 바꾸어 보여주는 방식)

    3. parent : 이 뷰를 포함하고 있는 부모 컨테이너 객체이다.

   

4. 하나의 아이템에 여러 정보를 담아 리스트뷰로 보여줄 때 해야 할 일들  (크게 4가지 존재) 

  종류

 정의 

 (1) 아이템을 위한 XML레이아웃 정의하기

 - 리스트뷰에 들어갈 각 아이템의 레이아웃을 XML로 정의함

 - 선택위젯에서 각각의 아이템은 동일한 레이아웃을 가진뷰가 반복적으로 보여짐

    각각의 아이템을 위한 XML레이아웃이 필요함 

 (2) 아이템을 위한 뷰 정의하기

 - 리스트뷰에 들어갈 각 아이템을 하나의 뷰로 정의

   이 뷰는 여러 개의 뷰를 담고 있는 뷰그룹이어야 함

 - 어댑터의 getView()메소드에서 리턴해 줄 뷰를 별도의 클래스로 정의하여 사용

 (3) 어댑터 정의하기

 - 데이터 관리 역할을 하는 어댑터 클래스를 만들고 그 안에 각 아이템으로

    표시할 뷰를 리턴하는 getView()메소드를 정의함 

 (4) 리스트뷰 정의하기

 - 화면에 보여줄 리스트뷰를 만들고 그 안에 데이터가 선택되었을 때

   호출될 시트너 객체를 정의함 

 

5. 스피터

   1. 정의 : 여러 아이템 중에서 하나를 선택하는 전형적인 위젯

   2. xml 레이아웃에 <Spinner>태그를 이용해 추가한 후 사용할 수 있다.

 

6. ArrayAdapter

    1. 정의 : 배열로 된 데이터 이용

    2. Reference

       - public ArrayAdapter(Context context, int textViewResourceId, T[] objects)

          . context : Context객체이므로 액티비티인 this를 전달하면 됨

          . textViewResourceId : 뷰를 초기화할 때 사용되는 XML레이아웃의 리소스 ID값으로 이코드에서는

                                              android.R.layout.simple_spinner_item과 같은 형식을 전달하면 됨

          . objects : 아이템으로 보일 문자열 데이터들의 배열임

 

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

ListView 기본 개념  (0) 2017.01.18
ListView 기초예제1  (0) 2016.12.06
Posted by 농부지기
,

[ListView 기초예제1]                                                   //참고 URL : http://iotsw.tistory.com/106

- 사용자가 정의한 데이터 목록을 아이템 단위로 구성하여 화면에 출력하는 ViewGroup의 한 종류
- 리스트뷰의 아이템들은 세로방향으로 나열되고 아이템의 갯수가 많아짐에 따라 리스트뷰에 표시될 내용
  이 리스트의 크기보다 커지면 스크롤이 제공됨
- 리스트뷰에 표시되는 아이템은 단순히 Text만 출력하는 기본 리스브튜 구조도 있고, 다양항 위젯의 조합
  으로 원하는 View의 조합으로 커스텀(사용자회된)형태의 구조도 만들 수 있음

 

[MainActivity.java]

  1. Adapter 란 : UI(android.R.layout.simple_list_item_1)와 Data(listItems)를 가지고 있게 되는데.
                      UI를 Inflation해서 Data에 바인딩하는 역할을 한다.

     . ListView Adapter

    

     - 어탭터는 하나의 뷰를 그릴 UI와 모든 아이템들의 데이터가 필요
     - 어댑터는 아이템들 데이터셋으로부터 하나씪 꺼내서 뷰를 그릴 UI에 데이터를 바인딩해서 하나의 뷰를
        만들어서 리스트뷰에 배치하는 작업을 모든 아이템에 대해 반복적으로 수행함

 
public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private String[] listItems//리스트뷰에 데이터들 담을 수 있는 껍데기
    private ArrayAdapter<String> adapter; //어댑터 만들기

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

        listView = (ListView)findViewById(R.id.lv);
        listItems = new String[] {"대한민국", "영국", "프랑스", "알제리", "배트남"};  //리스트뷰에 담을 데이터

        //Adapter는 UI(android.R.layout.simple_list_item_1)와 Data(listItems)를 가지고 있게 되는데.
        //          UI를 Inflation해서 Data에 바인딩하는 역할을 한다.
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);

        listView.setAdapter(adapter);

        //이벤트 처리
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //Toast.makeText(MainActivity.this,(String)parent.getItemAtPostion(position), 0).show();  //오류 발생
                Toast.makeText(MainActivity.this, position + "번째 클릭", Toast.LENGTH_SHORT).show();
            }
        });

        /*
           정의 : 롱클릭 이벤트  (오래 눌렀을 경우 수행)
           -return true 면  : 이벤트를 먹어버려서 setOnItemClickListener()를 수행하지 않음
           -return false 면 : setOnItemClickListener()를 수행함.
         */
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this, (String)parent.getItemAtPosition(position)+ "를 오래누름", Toast.LENGTH_SHORT).show();
                return false;
            }
        });

    }
}

 

 

[ activity_main.xml]

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.farmer.listview001.MainActivity">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"  />
</RelativeLayout>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

ListView 기본 개념  (0) 2017.01.18
ListView 정의  (0) 2016.12.07
Posted by 농부지기
,

[ Fragment 기초 예제 3 ]                                    0. 참고 : DO IT 안드로이드 (02-10 : SampleFragment2)

 

1. Layout3개

   - activity_main.xml                    fragment_list.xml                    fragment_viewer.xml

     

2. 실행 화면

    

 

 

1. activity_main.xml

   - <fragment> 2개를 위/아래로 가지고 있음

   - android:name : Fragment를 넣을 객체명 지정

   -

 

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

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="org.androidtown.fragment.ListFragment"
        android:id="@+id/listFragment" />

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="org.androidtown.fragment.ViewerFragment"
        android:id="@+id/viewerFragment" />


</LinearLayout> 

 

2. fragment_list.xml

   -

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

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView" />
</LinearLayout>

 

3. fragment_viewer.xml

   -

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

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/imageView"
        android:src="@drawable/dream01"/>

</LinearLayout>

 

4. MainActivity.java

   - drawable 폴더 밑으로 dream01.png, dream02.png, dream03.png 이미지 3개 필요

   -

public class MainActivity extends AppCompatActivity implements ListFragment.ImageSelectionCallback {
    ListFragment listFragment;
    ViewerFragment viewerFragment;

    int[] images = {R.drawable.dream01, R.drawable.dream02, R.drawable.dream03};

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

        FragmentManager manager = getSupportFragmentManager();
        listFragment = (ListFragment) manager.findFragmentById(R.id.listFragment);
        viewerFragment = (ViewerFragment) manager.findFragmentById(R.id.viewerFragment);
    }

    @Override
    public void onImageSelected(int position) {
        viewerFragment.setImage(images[position]);
    }
}

 

5. ListFragment.java

   -

public class ListFragment extends Fragment {
    String[] values = {"첫번째 이미지", "두번째 이미지", "세번째 이미지"};

    public static interface ImageSelectionCallback {
        public void onImageSelected(int position);
    }

    public ImageSelectionCallback callback;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof ImageSelectionCallback) {
            callback = (ImageSelectionCallback) context;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list, container, false);

        ListView listView = (ListView) rootView.findViewById(R.id.listView);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, values);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (callback != null) {
                    callback.onImageSelected(position);
                }
            }
        });

        return rootView;
    }
}

 

6. ViewerFragment.java

   -

public class ViewerFragment extends Fragment {
    ImageView imageView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_viewer, container, false);

        imageView = (ImageView) rootView.findViewById(R.id.imageView);

        return rootView;
    }

    public void setImage(int resId) {
        imageView.setImageResource(resId);
    }
}

 

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

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

[ Fragment 기초 예제 2 ]                                    0. 참고 : DO IT 안드로이드 (02-10 : SampleFragment)

 

1. 소스 이동 설명

   - activity_main.xml  -> fragment_main.xml <-> fragment_menu.xml

     실제 이동 방법은

        activity_main.xml  Layout에서  onFragmentChanged()  메소드를 이용해서 2개의 fragment를 교체(replace)해준다.

                  -> fragment_main.xml 

                  -> fragment_menu.xml

   - activity_main.xml 내부에 <fragment> 안에  fragment_main Layout을 넣는다.

   - fragment_main Layout에서 버튼을 클릭 하면 fragment_menu Layout을 open한다.

   - fragment_menu Layout 에서 [메인 화면 으로] 버튼 클릭 시    fragment_main Layout으로 간다.

   -

        <-> 

 

 

 

2. FragmentManage객체

   - 프래그먼트 매니저는 프래그먼트를 다루는 작업을 해주는 객체로써 프래그먼트를 추가,삭제 또는 교체등의 작업을 할 수 있게 해줌.

   - 그런데 이런 작업들은 프래그먼트를 변경할 때 오류가 생기면 다시 원래 상태로 돌릴 수 있어야 하므로 트랜젝션 객체를 만들어 실행한다.

   - 트랜젝션 객체는 beginTransaction()메소드를 호출하면 시작되고 commit()메소드를 호출하면 실행된다.

 

3. getFragmentManager(), getSupportFragmentManager() 의 동일점, 차이점

   - 동일점 : 동일한 기능을 수행하는 FragmentManager객체를 리턴

   - 차이점 : getSupportFragmentManager()메소드는 안드로이드 이전 버전들에서도 프래그먼트를 사용할 수 있도록 만든

                appcompat_v7라이브러리 프로젝트에서 지원하는 기능이므로 프로젝트를 만들 때 getSupportFragmentManager()메소드

                사용을 권장 한다.

                이는 MainActivity객체가 상속하는 AppCompatActivity클래스도 마찬가지여서 android.support.v7.app패키지 안에 있는

                AppCompatActivity클래스를 사용해야 한다.

 

 

 

1. activity_main.xml

   - <fragment> 가 필요 : 첫 activity_main Layout을 띄우면서 바로  fragment_main Layout을 이 <fragment>에 넣는다.

   - android:name="org.androidtown.fragment.MainFragment" :

   -

<?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:id="@+id/container"
    >

    <fragment
        android:id="@+id/mainFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="org.androidtown.fragment.MainFragment" />

</RelativeLayout>

 

2. MainActivity.java

   1. getSupportFragmentManager().findFragmentById()

      - Fragment는 뷰가 아니라서 Activity클래스에 있는 findViewById()메소드를 이용해서 찾을 수 없다.

         대신 프래그먼트르르 관리하는 FragmentManager객체의 findFragmentById()메소드를 이용해 찾을 수 있다.

      - 메인 프래그먼트는 findFragmentById() 메소드를 이용해 찾은 후 변수에 할당하고,

        메뉴 프래그먼트는 new연산자를 이용해 새로운 객체로 만든 후 변수에 할당한다.

   2. onFragmentChanged()
      - MainFragment.java에서 호출
      - activity_main Layout에서  2개의 Fragment를 교체 해준다.

   3. getSupportFragmentManager()

      - 메인 액티비티에 새로 추가할 메소드로 프래그먼트 매니저를 이용해 프래그먼트를 전환하는 메소드이다.

        이렇게 코드를 입력한 이유는 프래그먼트가 액티비티를 본더 만들었고 액티비티 관리를 시스템에서 하는 것처럼

        프래그먼트 관리를 액티비티가 하기 때문이며, 액티비티에서 프래그먼트를 전환하도록 만들어야 하기 때문이다.

public class MainActivity extends AppCompatActivity {
    MainFragment mainFragment;
    MenuFragment menuFragment;

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

        mainFragment = (MainFragment) getSupportFragmentManager().findFragmentById(R.id.mainFragment);
        menuFragment = new MenuFragment();
    }

    public void onFragmentChanged(int index) {
        if (index == 0) {
            getSupportFragmentManager().beginTransaction().replace(R.id.container, menuFragment).commit();
        } else if (index == 1) {
            getSupportFragmentManager().beginTransaction().replace(R.id.container, mainFragment).commit();
        }
    }
}

 

3. MainFragment.java

   -

public class MainFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_main, container, false);

        Button button = (Button) rootView.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity activity = (MainActivity) getActivity();
                activity.onFragmentChanged(0);
            }
        });

        return rootView;
    }
}

 

4. MenuFragment.java

   -

public class MenuFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_menu, container, false);

        Button button = (Button)rootView.findViewById(R.id.button);
        button.setOnClickListener(buttonListener);

        return rootView;
    }

    View.OnClickListener buttonListener = new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            Toast.makeText(getContext(), "메인 화면으로 가기 버튼 클릭", Toast.LENGTH_SHORT).show();
            //종료 안됨.
            //  --아래 2줄은 Fragment를 change해주는 소스임
            //  --MainActivity에 Fragment를 여러장 올려 놓고 서로 교체하는 소스임.
            //  --예url : http://blog.naver.com/ssy9137/220725822294
            //MainActivity activity = (MainActivity)getActivity();
            //activity.onFragmentChanged(-1);

            //getActivity().getFragmentManager().beginTransaction().remove(this).commit();  //this 오류 발생
            //getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();  //this 오류 발생
            //getActivity().getSupportFragmentManager().popBackStack();  //종료 안됨
            //getActivity().getFragmentManager().popBackStack();  //종료 안됨
            //getFragmentManager().popBackStack(); //종료 안됨
            //getActivity().onBackPressed();  //아에 앱이 종료 됨. 즉 Main Activity 로 돌아가지 않음.
            //getActivity().finish();  //아에 앱이 종료 됨. 즉 Main Activity 로 돌아가지 않음.

            //종료 안됨.
            //FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            //transaction.addToBackStack(null);

            //종료 잘 됨.
            //  아래 방식은 fragment를 종료하는 방법임
            //FragmentManager manager = getActivity().getSupportFragmentManager();
            //manager.beginTransaction().remove(MenuFragment.this).commit();
            //manager.popBackStack();

            //MainActivity.java 의 replace문법으로 fragment를 교체해 준다.
            MainActivity activity = (MainActivity) getActivity();
            activity.onFragmentChanged(1);
        }
    };
}

 

5. fragment_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="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="메인 프래그먼트"
        android:id="@+id/textView"
        android:textSize="30dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="메뉴 화면으로"
        android:id="@+id/button" />
</LinearLayout>

 

6. framgnet_menu.xml

   -

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="메뉴 프래그먼트"
        android:id="@+id/textView"
        android:textSize="30dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="메인 화면으로"
        android:id="@+id/button" />
</LinearLayout>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

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

 

[ AlertDialog ]

 

1. 정의

   - 대화상자를 보여주는 가장 단순한 객체

 

2. 주요 메소스

   - setTitle() : 타이틀 설정

   - setMessage() : 메세지 내용 설정

   - setPositiveButton(), setNegativeButton() : 예, 아니오  - 버튼 설정

     . 이 메소드에는 OnclickListener()를 설정할 수 있다.

 

3. 사용예

   - button클릭 시 onButton1Clicked() Event가 호출 되어 대화상자를 띄워준다.

 

 

public class MainActivity extends AppCompatActivity {
    TextView textView1;
    String msg;

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

        textView1 = (TextView) findViewById(R.id.textView1);

    }

    /**
* 버튼을 눌렀을 때 대화상자 객체를 생성하는 메소드를 호출
     * @param v
     */
    public void onButton1Clicked(View v) {
        AlertDialog dialog = createDialogBox();
        dialog.show();
    }

    /**
     * 대화상자 객체 생성
     */
    private AlertDialog createDialogBox(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("안내");
        builder.setMessage("종료하시겠습니까?");
        builder.setIcon(android.R.drawable.ic_dialog_alert);

        // 예 버튼 설정
        builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                msg = "예 버튼이 눌렀습니다. " + Integer.toString(whichButton);
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });

        // 취소 버튼 설정
        builder.setNeutralButton("취소",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                msg = "취소 버튼이 눌렸습니다. " + Integer.toString(whichButton);
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                //textView1.setText(msg);
            }
        });

        // 아니오 버튼 설정
        builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                msg = "아니오 버튼이 눌렸습니다. " + Integer.toString(whichButton);
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });

        // 빌더 객체의 create() 메소드 호출하면 대화상자 객체 생성
        AlertDialog dialog = builder.create();

        return dialog;
    }

 

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

Toast  (0) 2016.12.04
Posted by 농부지기
,

Toast

[Android] - 개념/Message 2016. 12. 4. 18:59

 

[ Toast ]

 

1. Code

   - Toast.makeText(Context context, String message, int duration)

   - Context : 일반적으로 Context클래스를 상속한 액티비티를 사용

   -

 

2. 위치및 모양 변경

   - setGravity(int gravity, int xOffset, int yOffset)

   - setMargin(float horizontalMargin, float verticalMargin)

 

3. 추가 메소드

   - setView(Layout layout);  --토스트가 보이는 뷰 설정

   - show();  --토스트를 보여줌

 

4. 별도 Layout을 이용해서 Toast 보여주기

 

 

   [ 4.1 MainActivity.java ]

 

public class MainActivity extends AppCompatActivity {

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

    public void onButton1Clicked(View v) {
        // 토스트의 모양을정의하고 있는 레이아웃을 인플레이션합니다.
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toastborder, (ViewGroup) findViewById(R.id.toast_layout_root));

        // 레이아웃의 텍스트뷰에 보여줄 문자열을 설정합니다.
        TextView text = (TextView) layout.findViewById(R.id.text);
        text.setText("Hello My Android!");

        // 토스트 객체를 만듭니다.
        Toast toast = new Toast(this);
        toast.setGravity(Gravity.CENTER, 0, -100);
        toast.setDuration(Toast.LENGTH_SHORT);

        // 토스트에 뷰를 설정합니다. 이 뷰가 토스트로 보여집니다.
        toast.setView(layout);
        toast.show();
    }
}

 

   [ 4.2 activity_main.xml ]

 

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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="토스트 보여주기"
      android:textSize="20dp"
      android:onClick="onButton1Clicked" />

</RelativeLayout>

 

   [ 4.3 toastborder.xml ] - toast를 보여줄 Layout

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/toast_layout_root"
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="10dp"
   >
   <TextView
      android:id="@+id/text"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:padding="20dp"
      android:background="@drawable/toast"
      />
</LinearLayout>

 

   [ 4.4 toast.xml ]

    - 별도 xml을 이용해서 Toast 색상정의

   - /res/drawable/toast.xml

   - setView()메소드를 이용해 토스트 객체에 설정한다.

 

<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle"
   >
   <stroke
      android:width="4dp"
      android:color="#ffffff00"
      />
   <solid
      android:color="#ff883300"
      />
   <padding
      android:left="20dp"
      android:top="20dp"
      android:right="20dp"
      android:bottom="20dp"
      />
   <corners
      android:radius="15dp"
      />
</shape>

 

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

AlertDialog  (0) 2016.12.04
Posted by 농부지기
,

[ Intent() 정의 ]

 

1. 정의

   - 패키지 : android.content.Intent

   - 역할 : 애플리케이션 구성요소 간에 작업 수행을 위한 정보를 전달하는 역할

 

2. 대표적 Method

  - 정의 : 다른 애플리케이션 구성요소에 인텐트를 전달할 수 있는 대표적인 메소드

  - startAcitivity()

    startActivityForResult()

    startService()

    bindService()

    broadcastIntent()

 

3. 각 Method별 설명

   - startAcitivity()             - 액티비티를 띄울 때 사용

                                    - 새로 띄우는 액티비티로부터 응답을 받을 필요가 없을 경우에 사용 

   - startActivityForResult()  - 띄웠던 액티비티 닫히고, 그 닫혔던 액티비티가 어떤건지 구분할 때 사용

                                    - 띄웠던 액티비티로부터 응답을 받을 필요가 있을 경우에 사용

   - startService()               - 서비스를 시작할때 사용

   - bindService()

   - broadcastIntent()         - 브로드캐스팅을 수행할 때 사용

 

4. 인텐트 필터

   - 시스템이 요청하는 인텐트의 정보를 받아 처리할 애플리케이션 구성요소를 찾기 위해 필요한 정보가 인텐트 필터이다.

   - 인텐트필터는 인텐트가 가지는 액션 정보를 동일하게 가질 수 있는데 이 인텐트를 해석하는 메커니즘은 기본적으로

     전달하고자 하는 대상 인텐트와 설치된 애플리케이션들이 가지는 인텐트 필터를 서로 비교하는 방식을 취하고 있다.

 

 

 

 

 

 

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

Intent를 이용해 Layout 띄우기  (0) 2016.12.04
Posted by 농부지기
,

[ Intent를 이용해 Layout 띄우기 ]

 

1. onClickLinstener()  안 에서 Layout 띄우기

   (즉, 클릭 Event에서 Layout 띄우기)

   - Intent intent = new Intent(getBaseContext(), AnotherActivity1.class);

   - Intent intent = new Intent(getApplicationContext(), AnotherActivity1.class);

   - Event에서는 Context()를 사용해야 됨.

     Event에서는 this를 사용할 수 없음.

 

2. ??

    Intent intent = new Intent(this AnotherActivity1.class);

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

Intent() 정의  (0) 2016.12.04
Posted by 농부지기
,

 

[ Layout에서 별도 Layout 띄우기 ]

1. 소스 흐름 순서

    - MainActivity.java 에서

      activity_main.xml Layout 에서  another1.xml   layout을 띄우거나, another2.xml   layout을 띄울 수 있다.

      activity_main.xml <-> another1.xml

                             <-> another2.xml

    - MainActivity.java에서 띄워야 할 화면들이 여러 개가 되면서 띄웠던 화면을 닫고 원래 Main화면으로 돌아 올 때

      어느 띠웠던 화면에서 돌아 왔는지 알아야 될때가 있다

      또한 띠웠던 액티비티로부터 응답(param)값 받아 처리해야 되는 경우도 있다.

      

      startActivityForResult()를 이용해서 이 문제를 해결 할 수 있다.

 

2. startActivityForResult(Intent intent, int requestCode)

   - intent : 띄울 Activity

   - requestCode : 띄워야할 화면이 여러개 일 때 구분하기 위한 정수값

                        띄운 화면에서 사용할게 아니고,  띄웠던 화면이 닫히고 다시 Main화면으로 왔을때

                        어떤 화면에 돌아 왔는지 알기 위한 값이다.

 

3. onActivityResult(int requestCode, int resultcode, Intent intent)

   - 정의 : 띄었던 화면이 닫히면 자동으로 호출 되는 메소드

   - requestCode : 어떤 화면에서 돌아 왔는지 구분값

   - resultcode : 응답을 보내 온 액티비티로부터 전달된 값으로 보통 성공(200), 실패(400) 결과 값이 전달됨

                      (그런데, 왜 난 -1 값이 찍힐까????)

   - intent : 띄웠던 화면의 intent.  argument값을 들이 넘겨저 온다.

               응답을 보내 온 액티비티로부터 전달한 인텐트로 필요한 데이터가 있을 때 인텐트에 데이터를 넣어 전달.

 

 

[ AndroidManifest.xml ] - 아래 2개의 activity tag가 존재 해야 inflate를 할 수 있다.

<activity android:name=".AnotherActivity1"/>
<activity android:name=".AnotherActivity2"/>

 

 

[ MainActivity.java ]

/**
* 인텐트를 이용해 새로운 액티비티를 띄우고 다시 돌아오는 방법에 대해 알 수 있습니다.
*
* @author Mike
*/
public class MainActivity extends AppCompatActivity {

    /**
     * 요청 코드 정의
     */
    public static final int REQUEST_CODE_ANOTHER1 = 1001;
    public static final int REQUEST_CODE_ANOTHER2 = 2002;

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

    public void onButton1Clicked(View v) {
        switch(v.getId()) {
            case R.id.button1:
                // 인텐트 객체를 만드는 방법 #1
                // 인텐트 객체를 만듭니다.
                //getBaseContext(), getApplicationContext() 둘다 가능

                //AnotherActivity1.class 대신  this를 사용하기도 하지만 Event에서는 this를 사용할 수 없다.
                Intent intent = new Intent(getBaseContext(), AnotherActivity1.class);
                //Intent intent = new Intent(getApplicationContext(), AnotherActivity1.class);

                // 액티비티를 띄워주도록 startActivityForResult() 메소드를 호출합니다.
                //  - startActivityForResult(Intent intent, int requestCode)
                //  - requestCode : 띠운 AnotherActivity가 닫힐 때
                startActivityForResult(intent, REQUEST_CODE_ANOTHER1);
                break;
            case R.id.button2:
                Intent intent2 = new Intent(getApplicationContext(), AnotherActivity2.class);
                startActivityForResult(intent2, REQUEST_CODE_ANOTHER2);
                break;
        }


        // 인텐트 객체를 만드는 방법 #2
        //Intent intent = new Intent();
        //ComponentName name = new ComponentName("org.androidtown.intent.basic", "org.androidtown.intent.basic.AnotherActivity");
        //intent.setComponent(name);

        //startActivityForResult(intent, REQUEST_CODE_ANOTHER);

    }

    /**
     * 띄웠던 액티비티닫히면  자동 호출되는 메소드
     *  - requestCode : 이때 띄워주는 액티비티가 여러개 일때 어떤건지 구분하기 위한 값.
     *                  띄워줄때 넘겨줫던 requestCode 값을 다시 받게 된다.
     *                  그래야 어떤 화면에서 돌아 왔는지 알 수 있기 때문이다.
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (requestCode == REQUEST_CODE_ANOTHER1) {
            Toast toast = Toast.makeText(getBaseContext(), "onActivityResult() 메소드가 호출됨. 요청코드 : " + requestCode + ", 결과코드 : " + resultCode, Toast.LENGTH_LONG);
            toast.show();

            if (resultCode == RESULT_OK) {
                String name = intent.getExtras().getString("name");
                toast = Toast.makeText(getBaseContext(), "응답으로 전달된 name : " + name, Toast.LENGTH_LONG);
                toast.show();
            }else if (resultCode == RESULT_CANCELED) {
                toast = Toast.makeText(getBaseContext(), "오류 발생", Toast.LENGTH_LONG);
                toast.show();
            }

        }else if (requestCode == REQUEST_CODE_ANOTHER2) {
            Toast toast = Toast.makeText(getBaseContext(), "onActivityResult() 메소드가 호출됨. 요청코드 : " + requestCode + ", 결과코드 : " + resultCode, Toast.LENGTH_LONG);
            toast.show();
        }
    }
}

 

 

 

[ AnotherActivity1.java ]  , AnotherActivity2.java 도 동일하게 생성

public class AnotherActivity1 extends Activity {
   Button backButton;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.another1);

        backButton = (Button) findViewById(R.id.backButton1);
     
      // 버튼을 눌렀을 때 메인 액티비티로 돌아갑니다.
        backButton.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
              // 객체를 만듭니다.
              Intent resultIntent = new Intent();
              resultIntent.putExtra("name", "mike");

                // 응답을 전달하고 이 액티비티를 종료합니다.
              setResult(RESULT_OK, resultIntent);
                finish();
         }
      });
    }
}

 

 

[ 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" >

   <LinearLayout
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:orientation="horizontal">
      <Button
         android:id="@+id/button1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="액티비티1 띄우기"
         android:textSize="10dp"
         android:onClick="onButton1Clicked"/>
      <Button
         android:id="@+id/button2"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="액티비티2 띄우기"
         android:textSize="10dp"
         android:onClick="onButton1Clicked"/>
   </LinearLayout>

   <TextView
      android:id="@+id/textView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@+id/button1"
      android:layout_marginTop="40dp"
      android:gravity="center_horizontal"
      android:text="위의 버튼을 누르면 새로운 액티비티가 띄워집니다."
      android:textSize="14dp"
      android:textColor="#ffad6535" />
</LinearLayout>

 

 

[ another1.xml ],   another2.xml 파일도 동일하게 생성

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="300dp"
    android:layout_height="400dp" >

    <Button
        android:id="@+id/backButton1"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="돌아가기"
        android:textSize="22dp"/>
   
   <TextView
      android:id="@+id/textView1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@+id/backButton1"
      android:layout_marginTop="20dp"
      android:gravity="center_horizontal"
      android:text="위의 버튼을 누르면 메인 액티비티로 돌아갑니다."
      android:textSize="14dp"
      android:textColor="#ffad6535" />

</RelativeLayout>

 

 

 

 

 

 

 

 

 

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

Layout에 다른 Layout넣기  (0) 2016.12.04
Posted by 농부지기
,

* 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 농부지기
,