Android Blank Fragment
What is a Fragment
Android Blank Fragment is a piece of an activity which enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-activity.
A Fragment represents a behavior or a portion of user interface in an Activity. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.
Step By Step Tutorial
In this Tutorial you will learn how to add a simple fragment in android app. In my previous tutorial you learn how to create a simple login page. I hope you know how to make a new project in android, if not please see my previous tutorial (How to make a login page).
Going further with my previous tutorial:
Step 1: add a blank fragment in your project.
Step 2: After click on Fragment (Blank) a next dialog box will appear. Give here the name of fragment.
Step 3: See this image and give the name SimpleBlankFragment and click on finish button.
Step 4: Now in this project I’m seeing that a new SimpleBlankFragment.java file with in Java folder and a new fragment_simple_blank.xml file with in a layout folder.
Step 5: Now I’m going to do some changes in my fragment_simple_blank.xml file. I make changes on TextView control. I add the padding and textview color. Following are the changes.
<TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="Hello This is my Simple Blank Fragment" android:padding="10dp" android:textColor="@color/colorPrimaryDark" />
Step 6: After make changes in layout file I make some changes in default SimpleBlankFragment.java file. Change the default imported package file.
Change into: import android.support.v4.app.Fragment;
Instead of: import android.app.Fragment;
Step 7: Add a line in MainActivity.java file “SimpleBlankFragment.OnFragmentInteractionListener”.
It should be look like this.
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SimpleBlankFragment.OnFragmentInteractionListener{
Step 8: After that add a method after onCreate() method or at the end of file.
@Override public void onFragmentInteraction(Uri uri){ }
Step 9: Now we need an option like navigation bar or menu bar which open fragment on click. So now we make new menu bar option “Show Fragment” in activity_main_drawer.xml file under Menu folder.
Go to res => Menu => activity_Main_drawer.xml
And add below mention line.
<item android:id="@+id/shw_fragment" android:icon="@android:drawable/ic_menu_compass" android:title="Show Fragment" />
Step 10: Now go to MainActivity.java file and find the method “onNavigationItemSelected” change the code into below mentioned code:
@Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.nav_camara) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } else if (id == R.id.shw_fragment) { Fragment fragment = new SimpleBlankFragment(); if(fragment!=null){ FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, fragment); ft.commit(); } return true; } return super.onOptionsItemSelected(item); }
Step 11: Now your code is completed and ready to debug. So click on run button or press Shift+F10 from your keyboard.
Following is the full source code of this tutorial.
fragment_simple_blank.xml
<FrameLayout 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="com.example.suraj.androidlogintutorial.SimpleBlankFragment"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="Hello This is my Simple Blank Fragment" android:padding="10dp" android:textColor="@color/colorPrimaryDark" /> </FrameLayout>
SimpleBlankFragment
import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SimpleBlankFragment 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 static SimpleBlankFragment newInstance(String param1, String param2) { SimpleBlankFragment fragment = new SimpleBlankFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public SimpleBlankFragment() { // Required empty public constructor } @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_simple_blank, 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(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Uri uri); } }
MainActivity.xml
import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SimpleBlankFragment.OnFragmentInteractionListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camara) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } else if (id == R.id.shw_fragment) { Fragment fragment = new SimpleBlankFragment(); if(fragment!=null){ FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, fragment); ft.commit(); } return true; } return super.onOptionsItemSelected(item); } @Override public void onFragmentInteraction(Uri uri){ } }
One thought on “Android Blank Fragment”