How to Use Fragments in Android

Why fragments, and when to use fragments instead of activities?

#1 & #2 what are the purposes of using a fragment & what are the
advantages and disadvantages of using fragments compared to using
activities/views/layouts?

Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;

  • The ActionBar. If you want tabs up there to navigate your app, you quickly see that ActionBar.TabListener interface gives you a FragmentTransaction as an input argument to the onTabSelected method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.

  • The FragmentManager handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.

  • You can use the cool ViewPager with a FragmentPagerAdapter to create swipe interfaces. The FragmentPagerAdapter code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.

  • Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.

  • You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use ActionBarSherlock and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like the ActionBar, with tabs, overflow, split action bar, viewpager etc.

Bonus 2

The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity() with data on it. The intent is passed on to all fragments of the activity you launch.

How to use Fragments in Android

Okie... Finally found a solution. Probably, it wasn't much of a change.

Check out the code below...

activity_main.XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<fragment
android:id="@+id/fragment_content_1"
android:name="com.example.fragmentexample.Fragment_1"
android:layout_width="0dip"
android:layout_weight="0.50"
android:layout_height="fill_parent" >
</fragment>

<fragment
android:id="@+id/fragment_content_2"
android:name="com.example.fragmentexample.Fragment_2"
android:layout_width="0dip"
android:layout_weight="0.50"
android:layout_height="fill_parent" >

<!-- Preview: layout=@layout/fragment_basic -->
</fragment>

</LinearLayout>

The layouts of fragment_fragment_1 and fragment_fragment_2 remain the same.

Fragment_1.Java

public class Fragment_1 extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub

View view = inflater.inflate(R.layout.fragment_fragment_1, container, false);

final EditText edtxtPersonName_Fragment = (EditText) view.findViewById(R.id.edtxtPersonName);
Button btnSayHi_Fragment = (Button) view.findViewById(R.id.btnSayHi);

btnSayHi_Fragment.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

String name = edtxtPersonName_Fragment.getText().toString();

FragmentManager fm = getFragmentManager();
Fragment_2 f2 = (Fragment_2) fm.findFragmentById(R.id.fragment_content_2);

if(f2 != null && f2.isInLayout())
{
f2.setName(name);
}

Activity activity = getActivity();

if(activity != null)
{
Toast.makeText(activity, "Say&ing Hi in Progress...", Toast.LENGTH_LONG).show();
}
}
});

return view;

}

}

Fragment_2.Java

public class Fragment_2 extends Fragment{

View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub

view = inflater.inflate(R.layout.fragment_fragment_2, container, false);
return view;
}

public void setName(String name)
{
TextView txtName = (TextView) view.findViewById(R.id.txtViewResult);
txtName.setText("Hi " + name);
}

}

Here is the ScreenShot...

Sample Image

What's the correct way to use Fragments?

It's a lot of personal preference and requirement really. I'm not a big believer of the "correct way" concept, if you achieve your goal then it's not wrong, but there may be a nicer way to do it.

For me it would depend on how many nested fragments each FragmentActivity handles. If you have a tree of nested fragments you can get into a mess with nested fragment stacks, etc.

http://developer.android.com/training/implementing-navigation/temporal.html

Personally, if I'm writing an application with lots of fragments I tend to have a single Activity which makes navigation a bit more manageable with a single Fragment stack as using multiple FragmentActivity instances will use multiple fragment stacks.

http://developer.android.com/training/implementing-navigation/index.html

You could consider the ViewPager approach which is great if you want to use a tabular and swiping navigation. Although if you have heavy scrollable content views I would be hesitant as for some individuals multi-directional gesture interfaces can be quite frustrating.

http://developer.android.com/training/implementing-navigation/lateral.html

If your code is clean, manageable and not leaking references then I would probably stick with what you have and wouldn't waste your time re-factoring it.

How to use fragments correctly

In your mainactivity.xml

Change this :

<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/main"/>

to

<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/main"/>

This will work because when you are using fragment tag then you need to set the class there in xml itself but when you are creating a fragment programatically like you are doing in this case, XML can have only a container in which fragment is inflated.

-

Update

Your code in MainActivity for adding fragment is incorrect. You are using support fragment hence you should use getSupportFragmentManager()

Make the following changes in your code.

Change in import statement of MainActivity.java:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

Change in code for adding fragment:

  FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
BlankFragment done = new BlankFragment();
fragmentTransaction.add(R.id.main, done, "frag");
fragmentTransaction.commit();

I have modified your code in here.
http://pastebin.com/BEqExkbN

How to use fragments with kotlin

savedInstanceState is nullable, yet you declared it as Bundle - it should be Bundle?.

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {

How to work with activities and fragments (Kotlin)

Solution of your crash-
you have not initialized MaterialButton

         fun logOut(view: View){
//Add this line
**var logoutButton= view.findViewById<MaterialButton>(R.id.logoutButton)**
//---------
logoutButton.setOnClickListener(View.OnClickListener {
FirebaseAuth.getInstance().signOut()
//view.context.startActivity(Intent(view.context, LogInActivity::class.java))
val intent = Intent(activity, LogInActivity::class.java)
activity?.startActivity(intent)
})
}


Related Topics



Leave a reply



Submit