본문 바로가기

Programming/Android

[Android] Fragment 연습하기 - FragmentTestJake

반응형

Fragment는 Activity와 같이 고유한 생명주기를 갖고 있으며 Activity내에서 또다른 Activity를 띄우는 것과 같은 효과를 낼 수 있어 복잡한 UI를 설계할 때에 필수적으로 사용되는 컴포넌트이다.

간단한 Fragment 예제를 가지고 Fragment를 어떻게 사용하는지 연습해보자.


예제 애플리케이션 컨셉은 간단한 메모장이다. 메모를 추가하면 페이지가 하나씩 생기고 위아래 버튼으로 페이지를 옮겨다닐 수 있다.

메모 저장을 위한 sqlite연동은 생략하고 진행하기로 한다.


Project name : FragmentTestJake


Project hierarchy : 




sources



package glowsoft.fragmenttestjake;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {
	Button btnUp, btnDown, btnAdd;

	List alFrgs;
	FragmentManager fm;
	FragmentTransaction frgTransaction;

	int maxPageNum = 0;
	int curPageNo = 0;

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	//must be called in onCreate()
	private void bindView() {
		btnUp = (Button) findViewById(R.id.btnUp);
		btnDown = (Button) findViewById(R.id.btnDown);
		btnAdd = (Button) findViewById(R.id.btnAdd);
	}

	//must be called in onCreate()
	private void addListeners() {
		View.OnClickListener ocl = new View.OnClickListener() {
			@Override
			public void onClick(View vBtnClicked) {
				selectPage(vBtnClicked);
			}
		};
		btnAdd.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				addPage();
			}
		});
		btnUp.setOnClickListener(ocl);
		btnDown.setOnClickListener(ocl);
	}


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

		fm = getFragmentManager();
		frgTransaction = fm.beginTransaction();

		alFrgs = new ArrayList<>();
		addPage();

		frgTransaction.replace(R.id.fragment_place, alFrgs.get(0));
		frgTransaction.commit();

		//must call these methods when start
		bindView();
		addListeners();
	}


	private void selectPage(View vBtnClicked) {
		if(vBtnClicked == findViewById(R.id.btnDown)) { //page up
			curPageNo = (curPageNo + 1) % alFrgs.size();
		} else if(vBtnClicked == findViewById(R.id.btnUp)) { //page down
			if(curPageNo > 0)
				curPageNo--;
			else
				curPageNo = alFrgs.size()-1;
		}
		frgTransaction = fm.beginTransaction();
		frgTransaction.replace(R.id.fragment_place, alFrgs.get(curPageNo));
		frgTransaction.commit();
	}

	private void addPage() {
		Date currentTime = Calendar.getInstance().getTime();
		alFrgs.add(FrgPage.newInstance(
				Integer.toString(++maxPageNum), "jake", sdf.format(currentTime)));
	}
}



package glowsoft.fragmenttestjake;

import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Random;

public class FrgPage extends Fragment {
	private static final String ARG_PARAM1 = "memo_id";
	private static final String ARG_PARAM2 = "writer";
	private static final String ARG_PARAM3= "datetime";
	private String frgID;
	private String datetime;
	private String writer;

	TextView tvNum = null;
	EditText edtContent = null;
	TextView tvWriter = null;

	Random r = new Random();
	int bkgColor = Color.rgb(r.nextInt(64)+192,
			r.nextInt(64)+192,
			r.nextInt(64)+192);

	public static FrgPage newInstance(String param1, String param2, String param3) {
		FrgPage fragment = new FrgPage();
		Bundle args = new Bundle();
		args.putString(ARG_PARAM1, param1);
		args.putString(ARG_PARAM2, param2);
		args.putString(ARG_PARAM3, param3);
		fragment.setArguments(args);
		return fragment;
	}

	public FrgPage() {}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getArguments() != null) {
			frgID = getArguments().getString(ARG_PARAM1);
			writer = getArguments().getString(ARG_PARAM2);
			datetime = getArguments().getString(ARG_PARAM3);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	                         Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		final View view = inflater.inflate(R.layout.frg_page, container, false);

		tvNum = (TextView) view.findViewById(R.id.tvMemoNum);
		edtContent = (EditText) view.findViewById(R.id.edtContent);
		tvWriter = (TextView) view.findViewById(R.id.tvWriter);

		tvNum.setText("no."+frgID);
		tvWriter.setText("written by "+writer+" at "+datetime);

		view.setBackgroundColor(bkgColor);

		return view;
	}
}



<?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:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="vertical">

	<LinearLayout
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:orientation="horizontal">

		<Button
			android:id="@+id/btnUp"
			android:layout_width="0dp"
			android:layout_weight="1"
			android:layout_height="wrap_content"
			android:text="↑"/>

		<Button
			android:id="@+id/btnDown"
			android:layout_width="0dp"
			android:layout_weight="1"
			android:layout_height="wrap_content"
			android:text="↓"/>

		<Button
			android:id="@+id/btnAdd"
			android:layout_width="0dp"
			android:layout_weight="1"
			android:layout_height="wrap_content"
			android:text="+"/>

	</LinearLayout>

	<fragment
		android:id="@+id/fragment_place"
		android:name="glowsoft.fragmenttestjake.FrgPage"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		tools:layout="@layout/activity_main" />

</LinearLayout>



<RelativeLayout
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"
tools:context="glowsoft.fragmenttestjake.FrgPage">

    <TextView
        android:id="@+id/tvMemoNum"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:textSize="20dp" />
    
    <EditText
        android:id="@+id/edtContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvMemoNum"
        android:layout_margin="7dp"
        android:hint="memo here"
        android:textSize="20dp"/>
    
    <TextView
        android:id="@+id/tvWriter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:textSize="10dp"/>

</RelativeLayout>





반응형