Освой программирование играючи

Сайт Александра Климова

Шкодим

/* Моя кошка замечательно разбирается в программировании. Стоит мне объяснить проблему ей - и все становится ясно. */
John Robbins, Debugging Applications, Microsoft Press, 2000

Замещение фрагментов

Мы рассматривали пример программного добавления фрагмента при помощи метода add(), который является только одним из способом замещения контейнера фрагментом.

В более сложных программах, состоящих из нескольких фрагментов, используется метод replace(), который замещает фрагмент в контейнере другим фрагментом.

Рассмотрим на примере. Создадим активность с тремя кнопками и контейнером FrameLayout:


<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".TestActivity" >

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

        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Фрагмент 1" />

        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Фрагмент 2" />

        <Button
            android:id="@+id/button3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Фрагмент 3" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

</LinearLayout>

Создадим разметку для трёх фрагментов. Я приведу код только для первой разметки. В других можете использовать тот же код, только заменить текст в TextView, чтобы было понятно, о каком фрагменте идёт речь. По желанию можете также использовать разные картинки в ImageView:


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

    <TextView
        android:id="@+id/tvMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Фрагмент 1" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

Теперь напишем код для замещения фрагментов. Обратите внимание, что классы фрагментов мы используем в основном классе активности. Хотя в реальных проектах лучше выделить каждому классу фрагмента отдельный файл.


package ru.alexanderklimov.fragments;

import ...

public class TestActivity extends Activity {

	FrameLayout container;
	FragmentManager myFragmentManager;
	MyFragment1 myFragment1;
	MyFragment2 myFragment2;
	MyFragment3 myFragment3;
	final static String TAG_1 = "FRAGMENT_1";
	final static String TAG_2 = "FRAGMENT_2";
	final static String TAG_3 = "FRAGMENT_3";
	final static String KEY_MSG_1 = "FRAGMENT1_MSG";
	final static String KEY_MSG_2 = "FRAGMENT2_MSG";
	final static String KEY_MSG_3 = "FRAGMENT3_MSG";

	// класс для первого фрагмента
	public static class MyFragment1 extends Fragment {

		TextView textMsg;

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View view = inflater.inflate(R.layout.fragment1, null);
			textMsg = (TextView) view.findViewById(R.id.tvMessage);

			Bundle bundle = getArguments();
			if (bundle != null) {
				String msg = bundle.getString(KEY_MSG_1);
				if (msg != null) {
					textMsg.setText(msg);
				}
			}
			return view;
		}

		public void setMsg(String msg) {
			textMsg.setText(msg);
		}
	}

	// класс для второго фрагмента
	public static class MyFragment2 extends Fragment {

		TextView textMsg;

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View view = inflater.inflate(R.layout.fragment2, null);
			textMsg = (TextView) view.findViewById(R.id.tvMessage);

			Bundle bundle = getArguments();
			if (bundle != null) {
				String msg = bundle.getString(KEY_MSG_2);
				if (msg != null) {
					textMsg.setText(msg);
				}
			}
			return view;
		}

		public void setMsg(String msg) {
			textMsg.setText(msg);
		}
	}

	// класс для третьего фрагмента
	public static class MyFragment3 extends Fragment {

		TextView textMsg;

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View view = inflater.inflate(R.layout.fragment3, null);
			textMsg = (TextView) view.findViewById(R.id.tvMessage);

			Bundle bundle = getArguments();
			if (bundle != null) {
				String msg = bundle.getString(KEY_MSG_3);
				if (msg != null) {
					textMsg.setText(msg);
				}
			}
			return view;
		}

		public void setMsg(String msg) {
			textMsg.setText(msg);
		}
	}

	// метод основной активности
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_test);

		container = (FrameLayout) findViewById(R.id.container);

		Button button1 = (Button) findViewById(R.id.button1);
		Button button2 = (Button) findViewById(R.id.button2);
		Button button3 = (Button) findViewById(R.id.button3);

		button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				MyFragment1 fragment = (MyFragment1) myFragmentManager
						.findFragmentByTag(TAG_1);

				if (fragment == null) {

					Bundle bundle = new Bundle();
					bundle.putString(KEY_MSG_1, "Заменили на первый фрагмент");
					myFragment1.setArguments(bundle);

					FragmentTransaction fragmentTransaction = myFragmentManager
							.beginTransaction();
					fragmentTransaction.replace(R.id.container, myFragment1,
							TAG_1);
					fragmentTransaction.commit();

				} else {
					fragment.setMsg("Первый фрагмент уже загружен");
				}
			}
		});

		button2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				MyFragment2 fragment = (MyFragment2) myFragmentManager
						.findFragmentByTag(TAG_2);

				if (fragment == null) {

					Bundle bundle = new Bundle();
					bundle.putString(KEY_MSG_2, "Заменили на второй фрагмент");
					myFragment2.setArguments(bundle);

					FragmentTransaction fragmentTransaction = myFragmentManager
							.beginTransaction();
					fragmentTransaction.replace(R.id.container, myFragment2,
							TAG_2);
					fragmentTransaction.commit();

				} else {
					fragment.setMsg("Второй фрагмент уже загружен");
				}
			}
		});

		button3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				MyFragment3 fragment = (MyFragment3) myFragmentManager
						.findFragmentByTag(TAG_3);

				if (fragment == null) {

					Bundle bundle = new Bundle();
					bundle.putString(KEY_MSG_3, "Заменили на третий фрагмент");
					myFragment3.setArguments(bundle);

					FragmentTransaction fragmentTransaction = myFragmentManager
							.beginTransaction();
					fragmentTransaction.replace(R.id.container, myFragment3,
							TAG_3);
					fragmentTransaction.commit();

				} else {
					fragment.setMsg("Третий фрагмент уже загружен");
				}
			}
		});

		myFragmentManager = getFragmentManager();
		myFragment1 = new MyFragment1();
		myFragment2 = new MyFragment2();
		myFragment3 = new MyFragment3();

		if (savedInstanceState == null) {
			// при первом запуске программы
			FragmentTransaction fragmentTransaction = myFragmentManager
					.beginTransaction();
			// добавляем в контейнер при помощи метода add()
			fragmentTransaction.add(R.id.container, myFragment1, TAG_1);
			fragmentTransaction.commit();
		}
	}
}

При первом запуске приложения мы добавляем фрагмент в контейнер через метод add(). Далее при нажатии на одну из трёх кнопок мы заменяем фрагмент другим фрагментов. Если мы хотим заменить фрагмент на этот же фрагмент, то выводим сообщение, что данный фрагмент уже загружен.

Замещение фрагментов

Реклама