Android Chapter07 Fragments
Android Chapter07 Fragments
Fragments
Victor Matos
Cleveland State University
Portions of this page are reproduced from work created and shared by Google and used according to terms
described in the Creative Commons 3.0 Attribution License.
Fragments
• Android is a multitasking OS and its hardware specs allow for real
parallelism. However, at any given time only one activity per app can be
‘visible’ and ‘active’. This fact is rather limiting considering the extensive
screen area offered by larger devices (tablets, phablets, TV sets, etc).
Fragments offer an escape solution.
• A host activity’s GUI may expose any number of fragments. In this GUI
each fragment could be visible and active.
6-2
Fragments
• Fragments could access ‘global data’ held in the main activity to which
they belong. Likewise, they could send values of their own to the main
activity for potential dissemination to other fragments.
6-3
Fragments
Fragment2
(View 2)
main_holder_red
main_holder_blue
6-9
Example 1 – Dynamic Activity-Fragment Binding
This example shows a master-detail design. It is
based on three classes:
• MainActivity (host),
• FragmentBlue (master) and
• FragmentRed (detail)
6 - 10
Example 1 – Dynamic Activity-Fragment Binding
XML LAYOUT: activity_main.xml
<?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:baselineAligned="false"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/main_holder_blue"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" />
<FrameLayout
android:id="@+id/main_holder_red"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="vertical" />
</LinearLayout>
6 - 11
Example 1 – Dynamic Activity-Fragment Binding
XML LAYOUT: layout_blue.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_blue"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1Blue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Blue Layout..."
android:textColor="#ffffffff"
android:background="#ff0000ff"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="@+id/listView1Blue"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
6 - 12
Example 1 – Dynamic Activity-Fragment Binding
XML LAYOUT: layout_red.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_red"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1Red"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffff0000"
android:text="Red Layout..."
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1Red"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="10"
android:text="Click me!" />
</LinearLayout>
6 - 13
Example 1 – Dynamic Binding - MainActivity 1 of 3
//-----------------------------------------------------------------------
// GOAL: This example shows an Activity that includes two fragments.
// Fragments inflate layouts and then get attached to their corresponding
// layouts in the UI. The example includes two interfaces MainCallbacks
// and FragmentCallbacks. They implement inter-process communication from
// Main-to-fragments and from Fragments-to-Main.
// -----------------------------------------------------------------------
public class MainActivity extends Activity implements MainCallbacks {
FragmentTransaction ft;
FragmentRed redFragment;
FragmentBlue blueFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
6 - 14
Example 1 – Dynamic Binding - MainActivity 2 of 3
if (sender.equals("RED-FRAG")) {
// TODO: if needed, do here something on behalf of the RED fragment
}
if (sender.equals("BLUE-FRAG")) {
try {
// forward blue-data to redFragment using its callback method
redFragment.onMsgFromMainToFragment("\nSender: " + sender
+ "\nMsg: " + strValue);
} catch (Exception e) {
Log.e("ERROR", "onStrFromFragToMain " + e.getMessage());
}
}
6 - 15
Example 1 – Dynamic Binding - MainActivity 3 of 3
COMMENTS
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
context = getActivity(); // use this reference to invoke main callbacks
main = (MainActivity) getActivity();
} catch (IllegalStateException e) {
throw new IllegalStateException(
"MainActivity must implement callbacks");
}
} 6 - 17
Example 1 – Dynamic Binding - FragmentBlue 2 of 3
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
}// onCreateView
}// class
6 - 18
Example 1 – Dynamic Binding - FragmentBlue 3 of 3
COMMENTS
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Activities containing this fragment must implement interface: MainCallbacks
if (!(getActivity() instanceof MainCallbacks)) {
throw new IllegalStateException( " Activity must implement MainCallbacks");
}
main = (MainActivity) getActivity(); // use this reference to invoke main callbacks
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate res/layout_red.xml which includes a textview and a button
LinearLayout view_layout_red = (LinearLayout) inflater.inflate(
R.layout.layout_red, null);
// plumbing - get a reference to widgets in the inflated layout
txtRed = (TextView) view_layout_red.findViewById(R.id.textView1Red);
6 - 20
Example 1 – Dynamic Binding - FragmentRed 2 of 3
@Override
public void onClick(View v) {
String redMessage = "Red clock:\n" + new Date().toString();
txtRed.setText(redMessage);
main.onMsgFromFragToMain("RED-FRAG", redMessage);
}
});
return view_layout_red;
}
@Override
public void onMsgFromMainToFragment(String strValue) {
// receiving a message from MainActivity (it may happen at any point in time)
txtRed.setText("THIS MESSAGE COMES FROM MAIN:" + strValue);
}
}// FragmentRed
6 - 21
Example 1 – Dynamic Binding - FragmentRed 3 of 3
COMMENTS
6 - 22
Example 1 – Dynamic Binding - CallBacks
// method(s) to pass messages from fragments to MainActivity
6 - 23
Example 2 – Static Activity-Fragment Binding
This example shows the same master-detail design
introduced in the previous example. Like before, it
is based on three classes:
• MainActivity (host),
• FragmentRed (master) and
• FragmentBlue (detail)
6 - 24
Example 2 – Static Activity-Fragment Binding
• Static binding is simple and requires less programming than dynamic binding.
• This approach is appropriate for apps in which the interface retains the same
fragment(s) for their entire session.
• The Activity’s layout file uses the <fragment> element to mark the position and
size of the area on which a fragment instance is to be injected.
• The following attributes can be used to identify the fragment in case it needs to be
restarted (if none is provided the fragment is identified by the system’s id of the
fragment’s container id)
1. android:name="AppPackageName.FragmentClassName"
2. android:id="@id+/uniqueName" or
android:tag="string"
6 - 25
Example 2 – Static Activity-Fragment Binding
XML LAYOUT: activity_main.xml
<?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="horizontal" >
<fragment
android:id="@+id/main_holder_blue"
android:name="csu.matos.fragments.FragmentBlue"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/main_holder_red"
android:name="csu.matos.fragments.FragmentRed"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
</LinearLayout>
6 - 26
Example 2 – Dynamic Binding - MainActivity 1 of 3
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// NOTHING to do, fragments will be automatically created and added to the GUI
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
// get a reference to each fragment attached to the GUI
if (fragment.getClass() == FragmentRed.class ){
redFragment = (FragmentRed) fragment;
}
if (fragment.getClass() == FragmentBlue.class ){
blueFragment = (FragmentBlue) fragment;
}
6 - 27
Example 2 – Dynamic Binding - MainActivity 1 of 3
@Override
public void onMsgFromFragToMain(String sender, String strValue) {
Toast.makeText(getApplication(), " MAIN GOT MSG >> " + sender
+ "\n" + strValue, Toast.LENGTH_LONG).show();
if (sender.equals("RED-FRAG")){
//TODO: do here something smart on behalf of BLUE fragment
}
if (sender.equals("BLUE-FRAG")) {
redFragment.onMsgFromActivity("\nSender: " + sender + "\nMsg: " + strValue);
}//onMsgFromFragToMain
6 - 28
Example 2 – Static Binding - MainActivity 3 of 3
COMMENTS
6 - 29
Example 3 – Multiple-Fragments-One-Screen
• This example is a minor variation of Example1. The MainActivity displays a screen
simultaneously showing three independent fragments.
• All fragments are visible and active, providing multiple points of interaction with
the user. There are two instances of a ListView fragment, and a bottom layout
showing a design containing a TextView and a Button.
6 - 30
Example 3 – Multiple-Fragments-One-Screen 1 of 2
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/home1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#77ff0000"
android:orientation="vertical" /> 6 - 31
Example 3 – Multiple-Fragments-One-Screen 2 of 2
<View
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#ff000000" />
<LinearLayout
android:id="@+id/home3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</LinearLayout>
6 - 32
Example 4 – Saving Fragment State
A regular practice before leaving a fragment is to override its onSaveInstanceState
method to persist any state data inside a system’s managed bundle named outState.
Later, you may test for the existence of the saved state bundle and its contents inside
any of the following the methods: onCreate , onCreateView , onViewCreated, or
onViewStateRestored. This is know as a warm-start.
Observe that a fresh cold-start execution passes to the fragment a null bundle. Unlike
Activities, Fragments do to have an onRestoreInstanceState method.
@Override
public void onCreate(Bundle savedInstanceState) {
...
stateData = getArguments().getString("arg1", "cold-start");
if (savedInstanceState != null){
stateData = savedInstanceState.getString("arg1","warm-default");
}
}//onCreate
...
@Override
public void onSaveInstanceState(Bundle outState) {
...
outState.putString("arg1", stateData);
super.onSaveInstanceState(outState);
}//onSavedInstanceState 6 - 33
Operations on Fragments
There are various operations that affect the presence and visibility of
fragments dynamically bound to an activity. Those operations must be
applied inside the scope of a FragmentTransaction object.
show() / hide() Shows a previously hidden fragment (hidden but not destroyed).
attach() / detach() Attaches a fragment previously separated (detached) from the UI.
Detached fragments are invisible but not destroyed.
6 - 34
Operations on Fragments
Consider the following code sample on which a sequence of opposite
operations is applied to display a fragment.
FragmentTransaction ft = getFragmentManager().beginTransaction();
redFragment = FragmentRed.newInstance(intValue);
ft.add(R.id.main_holder, redFragment, "RED-TAG");
ft.hide(redFragment);
ft.show(redFragment);
ft.detach(redFragment);
ft.attach(redFragment);
ft.commit();
6 - 35
Using the BackStack to Recreate State
Android-OS introduced a special stack to help fragments keep state when the
user navigates from one UI to the other.
Remember that all Android devices include a Back button. When this button
is pressed in succession the app transitions to the previous screen shown by
the app until it ends. This mechanism provides a natural historical navigation
(also known as Back-Navigation). Another important pattern of navigation
known as Child-to-HighAncestor is discussed later.
ft.commit();
} catch (Exception e) {
Log.e("REMOVE>>> ", e.getMessage() );
}
6 - 38
Using the BackStack to Recreate State
Navigating Through the BackStack
In the previous transaction we reproduce the behavior of the Back key when
used for historical navigation.
2. The top element of the stack is inspected. First we obtain its tag and
later its numerical id by calling the method:
fragmentManager.getBackStackEntryAt(bsCount-1).getId().
6 - 39
Using the BackStack to Recreate State
Navigating Through the BackStack
The following code clears the current BackStack. All fragment transactions
pushed by calling the method ft.addToBackStack(…) are deleted. The app’s
UI is updated, removing all screens shown by fragments that put a reference
to themselves in the BackStack.
try {
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragmentManager.popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
ft.commit();
} catch (Exception e) {
Log.e("CLEAR-STACK>>> ", e.getMessage() );
}
6 - 40
Example 5 - Using the BackStack 1 of x
<TextView
android:id="@+id/textView1Main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#77ffff00"
android:text="Main Layout ..."
android:textAppearance="?android:attr/textAppearanceLarge" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal" >
<Button
android:id="@+id/button1MainShowRed"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ADD new RedFragment" /> 6 - 43
Example 5. LAYOUT: activity_main.xml 2 of 3
<Button
android:id="@+id/button2MainPop"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="POP Trans BackStack" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal" >
<Button
android:id="@+id/button4MainReplace"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="REPLACE new RedFragment" />
<Button
android:id="@+id/button3MainRemove"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="REMOVE RedFragment" />
</LinearLayout> 6 - 44
Example 5. LAYOUT: activity_main.xml 3 of 3
<FrameLayout
android:id="@+id/main_holder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:orientation="vertical" />
</LinearLayout>
MainCallbacks
package csu.matos.fragments;
// method(s) to pass messages from fragments to MainActivity
} 6 - 45
Example 5. LAYOUT: layout_red.xml 3 of 3
<TextView
android:id="@+id/textView1Red"
android:layout_width="match_parent"
android:layout_height="175dp"
android:layout_margin="20dp"
android:background="#ffff0000"
android:gravity="center"
android:text="Red Layout..."
android:textColor="@android:color/white"
android:textSize="35sp"
android:textStyle="bold" />
<Button
android:id="@+id/button1Red"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="Change Red Label" />
</LinearLayout> 6 - 46
Example 5. MainActivity 1 of 4
FragmentTransaction ft;
FragmentRed redFragment;
TextView txtMsg;
Button btnAddRedFragment;
Button btnReplaceRedFragment;
Button btnPop;
Button btnRemove;
int serialCounter = 0; //used to enumerate fragments
String redMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(v.getId() == btnAddRedFragment.getId() ){
addRedFragment(++serialCounter);
}
if(v.getId() == btnReplaceRedFragment.getId() ){
replaceRedFragment(++serialCounter);
}
if(v.getId() == btnPop.getId() ){
FragmentManager fragmentManager = getFragmentManager();
int counter = fragmentManager.getBackStackEntryCount();
txtMsg.setText("BACKSTACK old size=" + counter);
if(counter>0) {
// VERSION 1 [ popBackStack could be used as opposite of addBackStack() ]
// pop takes a Transaction from the BackStack and a view is also deleted
fragmentManager.popBackStackImmediate();
txtMsg.append("\nBACKSTACK new size=" + fragmentManager.getBackStackEntryCount() );
}
}//Pop 6 - 48
Example 5. MainActivity 3 of 4
if(v.getId() == btnRemove.getId() ){
FragmentManager fragmentManager = getFragmentManager();
int counter = fragmentManager.getBackStackEntryCount();
txtMsg.setText("BACKSTACK old size=" + counter);
// VERSION 2 -------------------------------------------------------
// Removes an existing fragment from the fragmentTransaction.
// If it was added to a container, its view is also removed from that
// container. The BackStack may remain the same!
Fragment f1 = fragmentManager.findFragmentByTag("RED-TAG");
fragmentManager.beginTransaction().remove(f1).commit();
txtMsg.append("\nBACKSTACK new size=" + fragmentManager.getBackStackEntryCount() );
// VERSION 3 -------------------------------------------------------
// Fragment f1 = fragmentManager.findFragmentById(R.id.main_holder);
// fragmentManager.beginTransaction().remove(f1).commit();
// txtMsg.append("\nBACKSTACK new size=" + fragmentManager.getBackStackEntryCount() );
}//Remove
}//onClick
@Override
public void onBackPressed() {
super.onBackPressed();
int counter = getFragmentManager().getBackStackEntryCount();
txtMsg.setText("BACKSTACK size=" + counter);
}
6 - 49
Example 5. MainActivity 4 of 4
// complete any pending insertions in the BackStack, then report its size
getFragmentManager().executePendingTransactions();
txtMsg.setText("BACKSTACK size =" + getFragmentManager().getBackStackEntryCount() );
}
// complete any pending insertions in the BackStack, then report its size
getFragmentManager().executePendingTransactions();
txtMsg.setText("BACKSTACK size =" + getFragmentManager().getBackStackEntryCount() );
}
}
6 - 50
Example 5. FragmentRed 1 of 2
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
@Override
public void onClick(View v) {
selectedRedText = "\nRed Clock:\n" + new Date().toString();
txtRed.append(selectedRedText);
// main.onMsgFromFragToMain("RED-FRAG", selectedRedText );
}
});
return view_layout_red;
}
}// FragmentRed
6 - 52
ViewPager2 + Fragment
Bước 2: Tạo mới và thiết kế giao diện cho đối tượng fragment, được sử
dụng để hiển thị các trang.
6 - 54
ViewPager2 + Fragment
Bước 4: Khai báo adapter
@NonNull
@Override
public Fragment createFragment(int position) {
return PageFragment.newInstance(pages.get(position));
}
@Override
public int getItemCount() {
return pages.size();
}
}
6 - 55
ViewPager2 + Fragment
Bước 5: Thiết lập view pager trong acvitity
List<String> pages;
Faker faker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
6 - 56
ViewPager2 + Fragment
Bước 6: Xử lý sự kiện khi page được chọn
viewPager.registerOnPageChangeCallback(new
ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// TODO:
}
});
viewPager.setCurrentItem(8);
6 - 57
TabLayout + ViewPager2 + Fragment
TabLayout có thể được sử dụng kết hợp với ViewPager để tạo giao diện
chọn trang hiển thị nhanh chóng.
6 - 58
TabLayout + ViewPager2 + Fragment
Cách sử dụng TabLayout kết hợp với ViewPager2 và Fragment
Bước 2: Khai báo TabLayout và ViewPager2 trong file xml của activity
6 - 59
TabLayout + ViewPager2 + Fragment
Bước 3: Khai báo adapter cho ViewPager2
@NonNull
@Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new RedFragment();
case 1:
return new GreenFragment();
default:
return new BlueFragment();
}
}
@Override
public int getItemCount() {
return 3;
}
}
6 - 60
TabLayout + ViewPager2 + Fragment
Bước 4: Thiết lập TabLayout và ViewPager2 trong activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
6 - 61
Build a flexible UI
When designing your application to support a wide range of screen sizes, you can
reuse your fragments in different layout configurations to optimize the user
experience based on the available screen space.
6 - 62
Build a flexible UI
Example 6. Master-detail app on portrait and landscape mode
63
Build a flexible UI
Example 6. Create layout for portrait and landscape orientation
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/master_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
64
Build a flexible UI
Example 6. Create layout for portrait and landscape orientation
<?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">
<FrameLayout
android:id="@+id/master_frame"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<FrameLayout
android:id="@+id/detail_frame"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
65
Build a flexible UI
Example 6. Create layout for master fragment
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
66
Build a flexible UI
Example 6. Create master fragment
public class MasterFragment extends Fragment {
OnShowDetailListener listener;
public MasterFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
67
Build a flexible UI
Example 6. Create master fragment
List<String> items;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_master, container, false);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (listener != null)
listener.showDetail(items.get(i));
}
});
return view;
}
interface OnShowDetailListener {
void showDetail(String text);
}
}
68
Build a flexible UI
Example 6. Create layout for detail fragment
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".DetailFragment"
android:background="#80F0">
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
69
Build a flexible UI
Example 6. Create detail fragment
public class DetailFragment extends Fragment {
TextView textView;
public DetailFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);
textView = view.findViewById(R.id.text_view);
Bundle bundle = getArguments();
if (bundle == null)
textView.setText("");
else
textView.setText(bundle.getString("selected"));
return view;
}
MasterFragment masterFragment;
DetailFragment detailFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fourth);
masterFragment.setShowDetailListener(this);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.master_frame, masterFragment);
ft.commit();
if (findViewById(R.id.detail_frame) != null) {
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.detail_frame, detailFragment);
ft.commit();
}
}
71
Build a flexible UI
Example 6. Create main activity
@Override
public void showDetail(String text) {
if (findViewById(R.id.detail_frame) == null) {
Bundle bundle = new Bundle();
bundle.putString("selected", text);
detailFragment.setArguments(bundle);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.master_frame, detailFragment);
ft.addToBackStack("detail");
ft.commit();
} else {
detailFragment.updateText(text);
}
}
}
72
Fragments
Questions ?