Harrix Блог

  • Списки статей
    • Все статьи
    • IT
    • Qt
    • C++
    • Сложение двух чисел
    • Web программированиe
    • FAQ
    • Latex
    • Установка программ
    • Мифы
    • Видео
    • Про фото
  • Проекты
  • Harrix.org
  • RSS
  • Контакты

Взаимодействие между фрагментами и активностью в Android Studio. Часть 1. Подготовка

Примеры передачи информации между фрагментами.

14.05.2017 Leave a Comment 8 185 просмотров

Передавать сообщения между элементами на одной активности легко. А как быть, если элементы находятся в разных фрагментах. В статье рассмотрены некоторые сценарии.

Все статьи цикла «Взаимодействие между фрагментами и активностью в Android Studio»:

  1. Часть 1. Подготовка
  2. Часть 2. Простые способы
  3. Часть 3. Через интерфейсы
  4. Часть 4. Через интенты
  5. Часть 5. Несколько фрагментов

Содержание

  • Создание проекта
  • Предварительная работа с главной активностью
  • Создаем фрагменты
  • Отображаем первый фаргмент
  • Точка сохранения 1

Создание проекта

Надеюсь, что вы умеете создавать проект под Android Studio.

Предварительная работа с главной активностью

Пусть разметка файла activity_main.xml будет такой.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical" >
 
    <FrameLayout
        android:id="@+id/fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
 
    <FrameLayout
        android:id="@+id/fragmentContainer2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
 
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

У нас есть два контейнера для фрагментов fragmentContainer и fragmentContainer2. Также на самой активности есть кнопка button, поле для ввода теста editText и поле для вывода теста textView.

В MainActivity.java проведем стандартную работу по созданию переменных, соответствующих элементам из xml разметки, а также пропишем обработчик клика кнопки.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.example.workwithfragments;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
 
public class MainActivity extends AppCompatActivity {
 
    private EditText editText;
    private TextView textView;
    private Button button;
    private FrameLayout fragmentContainer;
    private FrameLayout fragmentContainer2;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText = (EditText)findViewById(R.id.editText);
        textView = (TextView)findViewById(R.id.textView);
        button = (Button)findViewById(R.id.button);
        fragmentContainer = (FrameLayout)findViewById(R.id.fragmentContainer);
        fragmentContainer2 = (FrameLayout)findViewById(R.id.fragmentContainer2);
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
            }
        });
    }
}

Создаем фрагменты

Нам нужно будет создать 3 фрагмента для разных манипуляций.

Создадим простой фрагмент Fragment1.

Разметку фрагмента поменяем на такую.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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"
    android:background="#FF33B5E5">
 
    <EditText
        android:id="@+id/editTextFragment1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName" />
 
    <Button
        android:id="@+id/buttonFragment1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="From Fragment1" />
 
    <TextView
        android:id="@+id/textViewFragment1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Java файл Fragment1.java фрагмента у меня выглядел так.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.example.workwithfragments;
 
 
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
 
/**
* A simple {@link Fragment} subclass.
*/
public class Fragment1 extends Fragment {
 
 
    public Fragment1() {
        // Required empty public constructor
    }
 
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment1, container, false);
    }
 
}

Аналогично, как и для активности, сюда внес переменные, отвечающие за элементы из xml файла + обработка клика кнопки.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.example.workwithfragments;
 
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class Fragment1 extends Fragment {
 
    private EditText editTextFragment1;
    private TextView textViewFragment1;
    private Button buttonFragment1;
 
    public Fragment1() {
        // Required empty public constructor
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
 
        editTextFragment1 = (EditText) view.findViewById(R.id.editTextFragment1);
        textViewFragment1 = (TextView) view.findViewById(R.id.textViewFragment1);
        buttonFragment1 = (Button) view.findViewById(R.id.buttonFragment1);
 
        buttonFragment1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
        });
 
        return view;
    }
 
}

Обратите внимание, что я немного поменял строчку:

1
return inflater.inflate(R.layout.fragment_fragment1, container, false);

Также в фрагментах немного по другому выглядит вызов findViewById(). И работаем с элементами в методе onCreateView().

Аналогично создаем Fragment2.

Xml разметка.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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"
    android:background="#FF99CC00">
 
    <EditText
        android:id="@+id/editTextFragment2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName" />
 
    <Button
        android:id="@+id/buttonFragment2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="From Fragment2" />
 
    <TextView
        android:id="@+id/textViewFragment2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Java файл фрагмента Fragment2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.example.workwithfragments;
 
 
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
 
public class Fragment2 extends Fragment {
 
    private EditText editTextFragment2;
    private TextView textViewFragment2;
    private Button buttonFragment2;
 
    public Fragment2() {
        // Required empty public constructor
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_fragment2, container, false);
 
        editTextFragment2 = (EditText) view.findViewById(R.id.editTextFragment2);
        textViewFragment2 = (TextView) view.findViewById(R.id.textViewFragment2);
        buttonFragment2 = (Button) view.findViewById(R.id.buttonFragment2);
 
        buttonFragment2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
            }
        });
 
        return view;
    }
 
}

Аналогично создаем Fragment3.

Xml разметка.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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"
    android:background="#FFFFBB33">
 
    <EditText
        android:id="@+id/editTextFragment3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName" />
 
    <Button
        android:id="@+id/buttonFragment3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="From Fragment3" />
 
    <TextView
        android:id="@+id/textViewFragment3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Java файл фрагмента Fragment3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.example.workwithfragments;
 
 
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class Fragment3 extends Fragment {
 
    private EditText editTextFragment3;
    private TextView textViewFragment3;
    private Button buttonFragment3;
 
    public Fragment3() {
        // Required empty public constructor
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_fragment3, container, false);
 
        editTextFragment3 = (EditText) view.findViewById(R.id.editTextFragment3);
        textViewFragment3 = (TextView) view.findViewById(R.id.textViewFragment3);
        buttonFragment3 = (Button) view.findViewById(R.id.buttonFragment3);
 
        buttonFragment3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
            }
        });
 
        return view;
    }
 
}

Отображаем первый фаргмент

Задача. При запуске приложения в контейнер активности fragmentContainer должен загрузиться первый фрагмент Fragment1.

Решение. Будем использовать FragmentManager.

1
2
3
4
5
6
7
8
9
FragmentManager fm = getSupportFragmentManager();
 
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
    fragment = new Fragment1();
    fm.beginTransaction()
            .add(R.id.fragmentContainer, fragment)
            .commit();
}

Теперь при запуске приложения в первом контейнере появится первый фрагмент.

Точка сохранения 1

Дальше в коде я буду ссылаться на эту точку сохранения. Вы должны будете откатить программу к этому моменту: когда в активности отображается первый фрагмент при старте и всё.

Код MainActivity.java в точке сохранения 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.example.workwithfragments;
 
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
 
public class MainActivity extends AppCompatActivity {
 
    private EditText editText;
    private TextView textView;
    private Button button;
    private FrameLayout fragmentContainer;
    private FrameLayout fragmentContainer2;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText = (EditText)findViewById(R.id.editText);
        textView = (TextView)findViewById(R.id.textView);
        button = (Button)findViewById(R.id.button);
        fragmentContainer = (FrameLayout)findViewById(R.id.fragmentContainer);
        fragmentContainer2 = (FrameLayout)findViewById(R.id.fragmentContainer2);
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
 
        FragmentManager fm = getSupportFragmentManager();
 
        Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
        if (fragment == null) {
            fragment = new Fragment1();
            fm.beginTransaction()
                    .add(R.id.fragmentContainer, fragment)
                    .commit();
        }
    }
}

Код Fragemnt1.java в точке сохранения 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.example.workwithfragments;
 
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class Fragment1 extends Fragment {
 
    private EditText editTextFragment1;
    private TextView textViewFragment1;
    private Button buttonFragment1;
 
    
 
    public Fragment1() {
        // Required empty public constructor
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
 
        editTextFragment1 = (EditText) view.findViewById(R.id.editTextFragment1);
        textViewFragment1 = (TextView) view.findViewById(R.id.textViewFragment1);
        buttonFragment1 = (Button) view.findViewById(R.id.buttonFragment1);
 
        buttonFragment1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
 
        return view;
    }
}

Файл Fragment2.java.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.example.workwithfragments;
 
 
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
 
public class Fragment2 extends Fragment {
 
    private EditText editTextFragment2;
    private TextView textViewFragment2;
    private Button buttonFragment2;
 
    public Fragment2() {
        // Required empty public constructor
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_fragment2, container, false);
 
        editTextFragment2 = (EditText) view.findViewById(R.id.editTextFragment2);
        textViewFragment2 = (TextView) view.findViewById(R.id.textViewFragment2);
        buttonFragment2 = (Button) view.findViewById(R.id.buttonFragment2);
 
        buttonFragment2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
            }
        });
 
        return view;
    }
 
}

Файл Fragment3.java.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.example.workwithfragments;
 
 
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class Fragment3 extends Fragment {
 
    private EditText editTextFragment3;
    private TextView textViewFragment3;
    private Button buttonFragment3;
 
    public Fragment3() {
        // Required empty public constructor
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_fragment3, container, false);
 
        editTextFragment3 = (EditText) view.findViewById(R.id.editTextFragment3);
        textViewFragment3 = (TextView) view.findViewById(R.id.textViewFragment3);
        buttonFragment3 = (Button) view.findViewById(R.id.buttonFragment3);
 
        buttonFragment3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
            }
        });
 
        return view;
    }
 
}

Следующая часть Часть 2. Простые способы.


Статьи по теме:

  1. Создание простейшего Android приложения в Eclipse
  2. Пример подключения Jsoup в Android Studio
  3. Установка связки Android Studio и IntelliJ IDEA
  4. Взаимодействие между фрагментами и активностью в Android Studio. Часть 2. Простые способы

IT Andoid, Android Studio, Java

© 2014 Harrix