Tuesday, May 14, 2013

Simple Fragment Transactions

What we are going to do here is a simple Activity with a button. When we click that button a Fragment Transaction takes place and we add the Fragment's layout.

1. You start a new Project and you are using support library if you target API less than 11. So first add the support lib to the project.

2. In my case I'm extending FragmentActivity ( i'm using minimum sdk version 8  ) or for API 11 and above you can use just Activity.

3.  First we are going to create the Fragment.

We extend Fragment class, inflate Fragment's layout at onCreateView() method and declare an Interface for future communication between Fragment and Activity.
So our code is here :


public class Fragment_A extends Fragment {

protected static final String TAG = "FRAGMENTS_A";
private CallbackInterface listener;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_a_layout, container, false);

        return view; //returns view
    }
 
    // ********** declare INTERFACE ***************** //
 
    public interface CallbackInterface {
    public void onSomethingSelected(int position);
      }      

 
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
     
        // This makes sure that the container activity has implemented the callback interface. If not, it throws an exception
        try {
            listener = (CallbackInterface) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement CallbackInterface");
        }
    }
 
 
}

4. Fragment's layout 

<?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="@color/cool">
    
    <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Fragment A" />
</LinearLayout>


5. Now we are going to create our Activity :



public class MainActivity extends FragmentActivity  implements CallbackInterface  {

private static final String TAG = "passNumberTAG";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


final Button button = (Button) findViewById(R.id.button_id);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
         
       Fragment_A Frag_A = new Fragment_A();
         
       FragmentManager fm1 = getSupportFragmentManager();
        FragmentTransaction transaction = fm1.beginTransaction();
            
        transaction.add(R.id.fragment_container, Frag_A);
        transaction.commit();
            
        }
    });

}

@Override
public void onSomethingSelected(int position) {
Log.d(TAG, "Give me the result  " + position  );
position = position +1;
Log.d(TAG, "Give me the result  " + position  );

}

}

The part where the Transaction takes place is inside the click listener : 
        Fragment_A Frag_A = new Fragment_A();
          
        FragmentManager fm1 = getSupportFragmentManager();
        FragmentTransaction transaction = fm1.beginTransaction();
             
        transaction.add(R.id.fragment_container, Frag_A);
        transaction.commit();


-> new Fragment -> get FragmentManager -> beginTransaction -> add new layout and commit.


One last thing is the Activity's layout. The activity's layout includes an empty FrameLayoutthat acts as the fragment container. 



<RelativeLayout 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=".MainActivity" >

        <Button 
         android:id="@+id/button_id"
         android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="@string/button_text" />

        
        <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
        
        
</RelativeLayout>





No comments:

Post a Comment