Wednesday 18 October 2017

12. Fragment example in Android

12. Fragment example in Android


Quick Points:


  1. Create Activity and frame layout(i.e. Container for fragment)
  2. Create fragments
  3. Add button listener to add/replace the frame layout with different fragments

We will create one activity and 3 buttons. When We click on button, framelayout will be replaced by another fragment. Below is the java and xml code for the same.

FragmentTestActivity:

package tutorial.android.sachin4droid.androidtutorials;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import tutorial.android.sachin4droid.androidtutorials.fragment.Fragment1;
import tutorial.android.sachin4droid.androidtutorials.fragment.Fragment2;

public class FragmentTestActivity extends Activity implements Fragment2.OnFragmentInteractionListener,Fragment1.OnFragmentInteractionListener{

  Button button1Fragment,button2Fragment;
  //FrameLayout frameLayout;

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

      button1Fragment = (Button) findViewById(R.id.button1Fragment);
      button2Fragment = (Button) findViewById(R.id.button2Fragment);
     // frameLayout = (FrameLayout) findViewById(R.id.framelayout);

      button1Fragment.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              FragmentManager fm = getFragmentManager();
              FragmentTransaction ft = fm.beginTransaction();
              ft.addToBackStack("Fragment1");
              ft.add(R.id.framelayout, new Fragment1());
              ft.commit();

          }
      });
      button2Fragment.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {

              FragmentManager fm = getFragmentManager();
              FragmentTransaction ft = fm.beginTransaction();
              ft.add(R.id.framelayout, new Fragment2());
              ft.addToBackStack("Fragment2");
              ft.commit();

          }
      });

      FragmentManager fm = getFragmentManager();
      FragmentTransaction ft = fm.beginTransaction();
      ft.add(R.id.framelayout, new Fragment1());
      ft.commit();



  }

  @Override
  public void onFragmentInteraction(Uri uri) {

  }
}

Fragment1:

package tutorial.android.sachin4droid.androidtutorials.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import tutorial.android.sachin4droid.androidtutorials.R;


public class Fragment1 extends Fragment {


  public Fragment1() {
      // Required empty public constructo
  }



  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

  }

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

  // TODO: Rename method, update argument and hook method into UI event
  public void onButtonPressed(Uri uri) {

  }


  public interface OnFragmentInteractionListener {
      // TODO: Update argument type and name
      void onFragmentInteraction(Uri uri);
  }
}


Fragment2.java

package tutorial.android.sachin4droid.androidtutorials.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import tutorial.android.sachin4droid.androidtutorials.R;

/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link Fragment2.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link Fragment2#newInstance} factory method to
* create an instance of this fragment.
*/
public class Fragment2 extends Fragment {
  // TODO: Rename parameter arguments, choose names that match
  // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
  private static final String ARG_PARAM1 = "param1";
  private static final String ARG_PARAM2 = "param2";

  // TODO: Rename and change types of parameters
  private String mParam1;
  private String mParam2;

  private OnFragmentInteractionListener mListener;

  public Fragment2() {
      // Required empty public constructor
  }

  /**
   * Use this factory method to create a new instance of
   * this fragment using the provided parameters.
   *
   * @param param1 Parameter 1.
   * @param param2 Parameter 2.
   * @return A new instance of fragment Fragment2.
   */
  // TODO: Rename and change types and number of parameters
  public static Fragment2 newInstance(String param1, String param2) {
      Fragment2 fragment = new Fragment2();
      Bundle args = new Bundle();
      args.putString(ARG_PARAM1, param1);
      args.putString(ARG_PARAM2, param2);
      fragment.setArguments(args);
      return fragment;
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      if (getArguments() != null) {
          mParam1 = getArguments().getString(ARG_PARAM1);
          mParam2 = getArguments().getString(ARG_PARAM2);
      }
  }

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

  // TODO: Rename method, update argument and hook method into UI event
  public void onButtonPressed(Uri uri) {
      if (mListener != null) {
          mListener.onFragmentInteraction(uri);
      }
  }

  @Override
  public void onAttach(Context context) {
      super.onAttach(context);
      if (context instanceof OnFragmentInteractionListener) {
          mListener = (OnFragmentInteractionListener) context;
      } else {
          throw new RuntimeException(context.toString()
                  + " must implement OnFragmentInteractionListener");
      }
  }

  @Override
  public void onDetach() {
      super.onDetach();
      mListener = null;
  }

  /**
   * This interface must be implemented by activities that contain this
   * fragment to allow an interaction in this fragment to be communicated
   * to the activity and potentially other fragments contained in that
   * activity.
   * <p>
   * See the Android Training lesson <a href=
   * "http://developer.android.com/training/basics/fragments/communicating.html"
   * >Communicating with Other Fragments</a> for more information.
   */
  public interface OnFragmentInteractionListener {
      // TODO: Update argument type and name
      void onFragmentInteraction(Uri uri);
  }
}

Activity_fragment_test.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
  android:orientation="vertical"
  tools:context="tutorial.android.sachin4droid.androidtutorials.FragmentTestActivity"
  >



<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  >
  <Button
      android:id="@+id/button1Fragment"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button1" />

  <Button
      android:id="@+id/button2Fragment"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button2" />
</LinearLayout>

  <FrameLayout
      android:id="@+id/framelayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"

     >

  </FrameLayout>
</LinearLayout>

Fragment_fragment1.xml

<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:background="@android:color/holo_green_light"
  tools:context="tutorial.android.sachin4droid.androidtutorials.fragment.Fragment1">

  <!-- TODO: Update blank fragment layout -->
  <TextView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:text="I am in fragment 1"
      android:textSize="30dp"
      android:layout_gravity="center"/>

</LinearLayout>

Fragment_fragment2.xml

<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:background="@android:color/holo_orange_dark"
  tools:context="tutorial.android.sachin4droid.androidtutorials.fragment.Fragment2">

  <!-- TODO: Update blank fragment layout -->
  <TextView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:text="I am in fragment 2"
      android:textSize="30dp"
      android:layout_gravity="center"/>

</LinearLayout>


OUTPUT:



Thank you.

No comments:

Post a Comment

Extract error records while inserting into db table using JDBCIO apache beam in java

 I was inserting data into postgres db using apache beam pipeline. it works perfectly with JdbcIO write of apache beam library. But, now, i ...