Showing posts with label fragments. Show all posts
Showing posts with label fragments. Show all posts

Thursday, May 28, 2015

Check if we are in Dual Pane

This is a common problem and with a variety of solutions. In the solution I'll show you in a little while we check in our Activity if there is an id for the 2nd Fragment ( the one that will play the role of the DetailFragment ).

One common tactic is having two different versions of the xml layout we are wokring on. One in the layout folder and another one in the layout-sw600dp or whatever we define for the dual mode.

The 2nd file contains one more FrameLayout so what we basically have to do is check if the view is there. If its true then we are on a dual mode, if not then we are on a single mode.

First we define a Boolean isDualMode with false as an initial value.
Then on onCreate we check for the details id :  

View aView = findViewById(R.id.details);
if (aView != null) {
    isDualPane = true;
}

If thats true we add and commit the DetailsFragment also.

Full code for onCreate() :

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


        View aView = findViewById(R.id.details);
        if (aView != null) {
            isDualPane = true;
        }

        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        mainFragment = new MainFragment();

        if (isDualPane) {
            detailsFragment = new DetailsFragment();
            fragmentManager.beginTransaction().add(R.id.details, detailsFragment).commit();
        }

        fragmentManager.beginTransaction().add(R.id.main, mainFragment).commit();
        fragmentTransaction.commit();

    }

Tuesday, June 11, 2013

Add/Remove Fragment - Simple Example

What we are going to do :     

A View with a Button. When we click that Button a fragment is being added dynamically in our View. We click again and the fragment is being dynamically removed.


before and after Fragment Transaction took place


What we need: 
One Activity and one Fragment. In the Activity's layout we add two layout objects. That's a Button and a FrameLayout.
In Fragment's layout we have a TextView that contains just text in a color background

So the code for the Activity's and Fragment's layout is: 



Fragment's Layout :
 
Note the android:id = "@+id/fragment_container_1"  in the Activity's layout which is an identifier for our fragment. When we make Transactions like add we refer to a fragment by id.

Activity and Fragment :

Fragment Class :   is a typical Fragment class as we have seen it before


Activity Class :  onClick() begins Transaction. If state is null then we add and commit the fragment else we need to remove and commit again.
So the code is :

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>





Sunday, February 17, 2013

Fragments Tutorial - Simple 2 - Passing Data

Passing Data between Fragment and host Activity


To pass data from a Fragment to the host Activity we need to Define/declare an Interface and
Implement it on the Activity.

1. Declare an Interface on Fragment_A. 

public interface OnSomethingSelectedListener {
    public void passData(int position);
      }  

2. onAttach() : To be sure that Activity implements the Interface  onAttach callback method of Fragment_A  we instantiate an Instance of Ιnterface by casting the Activity  passed into onAttach().
The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.


@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 = (OnSomethingSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }



3. On Main Activity we implement the Interface like this :

public class MainActivity extends FragmentActivity implements OnSomethingSelectedListener


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


We just take the integer value parameter from the Fragment and add one to it.



4. A button on Fragment's layout so we can add onClick event
 

<button 
android:id="@+id/button_id" 
android:layout_height="wrap_content" 
android:layout_width="wrap_content" 
android:text="send Integer">
</button>

5. And on Fragment's onCreateView() we add the listener for the event:
Button button = (Button) view.findViewById(R.id.button_id);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.v(TAG, "onClick 1");
            listener.passData(5); //pass an Integer
        }
    });
We pass the value five to the method passData() Now when we click on the Button we open LogCat View and we see that value one has been added to the  value  of the parameter: