PENGEMBANGAN APLIKASI
PERANGKAT BERGERAK
(MOBILE)
Android Fragment
K Candra Brata
[email protected]
Mobille App Lab 2015-2016
Android Fragment
https://developer.android.com/training/basics/fragments/index.html
Fragment
An activity is a container for views
When you have a larger screen device than a phone like a
tablet it can look too simple to use phone interface here.
Fragments
Mini-activities, each with its own set of views
One or more fragments can be embedded in an Activity (attachable
and detachable).
You can do this dynamically as a function of the device type (tablet or
not) or orientation.
You can combine multiple fragments in a single activity to build a
multi-pane UI and reuse a fragment in multiple activities.
Fragment transactions can also be added to the activity backstack.
So when you hit the back button, fragment is undone.
Why Fragment?
Fragments memudahkan reuse components dalam layout yang
berbeda.
Contoh : membuat single-pane layout untuk smartphones dan
multi-pane layout untuk tablet.
Fragments juga dapat digunakan untuk layout berbeda secara
orientasi landscape maupun portrait pada smartphone.
The usage of fragments allows to design very flexible user
interfaces.
Why Fragment?
With situational layout you begin to encounter redundancy.
The layout in one case is very similar to the layout in another case (e.g.
Landscape or portrait).
You don't want to represent the same XML or Java code multiple times in
multiple places (Activity).
You sometimes want your code to behave situationally.
In portrait mode, clicking a button should launch a new activity.
In landscape mode, clicking a button should launch a new view.
Why Fragment?
Flexible & Dynamic
Why Fragment?
You might
decide to run
a tablet view in
portrait mode
with the handset
model of only
one fragment
in an Activity
Fragment
Lifecycle
Fragment in an Activity---Activity Lifecyle
influences
Activity paused all its fragments paused
Activity destroyed all its fragments paused
Activity running manipulate each fragment
independently.
Fragment transaction add, remove,
replace, etc.
adds it to a back stack that's managed by the activity
each back stack entry in the activity is a record of the
fragment transaction that occurred.
The back stack allows the user to reverse a fragment
transaction (navigate backwards), by pressing the Back
button.
Fragment
Lifecycle
Resumed:
The fragment is visible in the running
activity.
Paused:
Another activity is in the foreground
and has focus, but the activity in which
this fragment lives is still visible (the
foreground activity is partially
transparent or doesn't cover the entire
screen).
Stopped:
The fragment is not visible. Either the
host activity has been stopped or the
fragment has been removed from the
activity but added to the back stack.
A stopped fragment is still alive (all
state and member information is
retained by the system). However, it is
no longer visible to the user and will
be killed if the activity is killed.
Fragment
Lifecycle
Fragments
inside Activity
It lives in a ViewGroup inside the activity's view hierarchy
Fragment has its own view layout.
via XML: Insert a fragment into your activity layout by declaring the fragment
in the activity's layout file, as a <fragment> element,
via CODE: from your application code by adding it to an existing ViewGroup.
you may also use a fragment without its own UI as an invisible worker for the
activity.
Using fragments
in activity via XML
Activity layout XML can include fragments.
<! activity_name.xml >
<LinearLayout ...>
<fragment ...
android:id="@+id/id1"
android:name="ClassName1" />
<fragment ...
android:id="@+id/id2"
android:name="ClassName2" />
</LinearLayout>
Using fragments
in activity via XML
Activity A
Activity A Layout.xml
(Container view Group)
Fragmnt X
Fragment X
Fragment Y
Layout X.xml
Layout Y.xml
Fragment Y
Create fragments
in Java Code
Untuk membuat fragment , harus extend android.app.Fragment class atau salah satu
sub classnya, antara lain ListFragment, DialogFragment, PreferenceFragment atau
WebViewFragment.
Method getFragmentManager() dapat digunakan untuk add, remove dan replace fragments pada
layout activity.
Create
fragments
public class Name extends Fragment {
Public Name (){
// Consturctor
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup vg, Bundle bundle) {
// load the GUI layout from the XML
return inflater.inflate(R.layout.id, vg, false);
}
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
// ... any other GUI initialization needed
}
// any other code (e.g. Other life cycle and eventhandling)
}
Fragment vs Activity
(Event Handler)
Fragment code is similar to activity code,with a fewchanges:
Many activity methods aren't present in the fragment,but you can call
getActivity to access the activity the fragment is inside of.
Buttonb=(Button)findViewById(R.id.btn);
Buttonb=(Button) getActivity().findViewById(R.id.but);
Sometimes also use getView to refer to the activity's layout
Fragment Event handlers can not be attached in the XML anymore :(
Must be attached in Java code instead.
Fragment vs Activity
(Event Handler)
Activity layout XML :
<Button android:id="@+id/b1"
android:onClick="onClickB1".../>
sends the event to the Activity class.
Fragment XML:
<Buttonandroid:id="@+id/b1".../>
//in fragment's Java file
Button b = (Button) getActivity().findViewById(r.id.b1);
b.setOnClickListener(new View.OnClickListener(){
@Override public void onClick (View view){
//what ever code would have been in onClickB1
}
sends the event to the Fragment
});
fragment1_layout.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:background="#9ef"
android:orientation="vertical">
<EditText
android:id="@+id/editTextFragment"
android:layout_width="500px"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="10px"
android:hint="Fragment 1" />
<Button
android:id="@+id/btnFragment"
android:layout_width="500px"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10px"
android:text=EVENT FRAGMENT !!" />
</LinearLayout>
Fragment1.java
public class Fragment1 extends Fragment {
private View.OnClickListener click;
public Fragment1() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment1_layout
return inflater.inflate(R.layout.fragment1_layout, container, false);
}
@Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
final Button b = (Button) getActivity().findViewById(R.id.btnFragment);
final EditText e = (EditText) getActivity().findViewById(R.id.editTextFragment);
click = new View.OnClickListener() {
@Override
public void onClick(View v) {
e.setText("Event Invoked In Fragment");
}
};
b.setOnClickListener(click);
}
}
fragment2_layout.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:background="#666666"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="THIS IS FRAGMENT 2"
android:textColor="#ffff"
android:textSize="30px" />
<Button
android:id="@+id/btnFragment2"
android:layout_width="500px"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10px"
android:text="Call Other Activity" />
</LinearLayout>
Fragment2.java
public class Fragment2 extends Fragment {
public Fragment2() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment2_layout
return inflater.inflate(R.layout.fragmen2_layout, container, false);
}
@Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
final Button b2 = (Button) getActivity().findViewById(R.id.btnFragment2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent tlp = new Intent (Intent.ACTION_DIAL, Uri.parse("tel:123456789"));
startActivity(tlp);
}
});
}
}
activity_main.XML
<?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="horizontal">
<fragment
android:id="@+id/myFragment"
android:name="com.example.andra.demoevent.Fragment1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="@layout/fragment1_layout" />
<fragment
android:id="@+id/lmFragment"
android:name="com.example.andra.demoevent.Fragment2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
tools:layout="@layout/fragmen2_layout" />
</LinearLayout>
This Your package and name of your Fragment Class
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Fragment
Container
If the layout is to be dynamically modified in the program at
Runtime, use containers View Group to pass to Fragment
Managers.
(Container view Group)
Id:fragment_container
Fragmnt X
Create
The Fragment
Add or replace
To the FragmentManager
Commit
The changes
Fragment
BackStack
If you're adding multiple fragments to the same container, then
the order in which you add them determines the order they
appear in the view hierarchy
If you do not call addToBackStack() when you perform a
transaction that removes a fragment, then that fragment is
destroyed when the transaction is committed and the user
cannot navigate back to it.
Whereas, if you do call addToBackStack() when removing a
fragment, then the fragment is stopped and will be resumed if the
user navigates back.
Add Fragment at
RunTime (Activity)
//get FragmentTransaction associated with this Activity
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
//Create instance of your Fragment
ExampleFragment fragment = new ExampleFragment();
//Add Fragment instance to your Activity
fragmentTransaction.add(R.id.fragment_container, fragment);
//optional backstack
fragmentTransaction. addToBackStack(null);
fragmentTransaction.commit();
This points to the Activity ViewGroup in which the
fragment should be placed, specified by resource
ID
activity_main2.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="vertical">
<EditText
android:id="@+id/editTextActivity"
android:layout_width="500px"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="10px"
android:hint="write on me!" />
<Button
android:id="@+id/btnActivity"
android:layout_width="500px"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10px"
android:onClick="btnActivityClick"
android:text="Set View !!" />
<FrameLayout
android:id="@+id/ui_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText txtactivity;
private Button btnactivity;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
txtactivity = (EditText) findViewById(R.id.editTextActivity);
btnactivity = (Button) findViewById(R.id.btnActivity);
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
}
public void btnActivityClick(View v)
{
Fragment1 newfragment = new Fragment1();
fragmentTransaction.add(R.id.ui_container, newfragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
btnactivity.setEnabled(false);
}
}
Fragment1.java
public class Fragment1 extends Fragment {
private View.OnClickListener click;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public Fragment1() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment1_layout
return inflater.inflate(R.layout.fragment1_layout, container, false);
}
@Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
final Button b = (Button) getActivity().findViewById(R.id.btnFragment);
final EditText e = (EditText) getActivity().findViewById(R.id.editTextFragment);
fragmentManager = getActivity().getFragmentManager();
fragmentTransaction= fragmentManager.beginTransaction();
click = new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment2 lmfragment = new Fragment2();
fragmentTransaction.replace(R.id.ui_container, lmfragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
};
b.setOnClickListener(click);
}
}
Communication
between fragments
Assignment !!!!
One activity might contain multiple fragments.
The fragments may want to talk to each other.
Use activity's getFragmentManager method.
Its findFragmentById() method can access any fragment that has an id.
Activity act = getActivity();
FragmentClass fragment =
(FragmentClass) act.getFragmentManager()
.findFragmentById(R.id.fragmentId);
fragment.methodName(parameters);
Thanks!
QUESTIONS?
JOIN !!