Skip to main content

Featured post

Simple RecyclerView example with filter option in Android

Hi Guys, Maybe you all are expert in terms of using RecyclerView in android. This blog is simple example for using filter option with RecyclerView adapter. As for now you will instantiate RecyclerView and set the adapter to RecyclerView as following way. RecyclerView list = (RecyclerView) findViewById(R.id.list); list.setLayoutManager(new LinearLayoutManager(this)); list.setHasFixedSize(true); ArrayList&ltNumber&gt numbers = new ArrayList&lt&gt(); String ONEs[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN"}; String TENs[] = {"ZERO", "TEN", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY", "HUNDRED"}; String HUNDREDS[] = {"ZERO", "HUNDRED", "TWO HUND

Simple Fragments with Action Bar Example in Android


A Fragment represents a behavior of user interface in an Activity. A activity can have more than one fragments and also a fragment can be used in more than one activities.

Screen Shots of following tutorial.
Fragment 1



Fragment 2



See, Here I have used the Action Bar to navigate between tabs. Which were added in Android 3.0 (API level 11). So in lower version Action Bar doesn't work. You can take this post as Simple Action Bar tutorial in Android too :)

Following class works as a home for those two Fragments.
FragmentTabs.java

package com.example.fragmentexample;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;

public class FragmentTabs extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  final ActionBar bar = getActionBar();
  bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
  bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

  bar.addTab(bar
    .newTab()
    .setText("Simple")
    .setTabListener(
      new TabListener<FragmentCalculate.SimpleAddition>(this,
        "simple", FragmentCalculate.SimpleAddition.class)));
  bar.addTab(bar
    .newTab()
    .setText("List")
    .setTabListener(
      new TabListener<SampleList.SampleListFragment>(
        this, "list",
        SampleList.SampleListFragment.class)));
  if (savedInstanceState != null) {
   bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
  }
 }

 @Override
 protected void onSaveInstanceState(Bundle outState) {
  super.onSaveInstanceState(outState);
  outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
 }

 public static class TabListener<T extends Fragment> implements
   ActionBar.TabListener {
  private final Activity mActivity;
  private final String mTag;
  private final Class<T> mClass;
  private final Bundle mArgs;
  private Fragment mFragment;

  public TabListener(Activity activity, String tag, Class<T> clz) {
   this(activity, tag, clz, null);
  }

  public TabListener(Activity activity, String tag, Class<T> clz,
    Bundle args) {
   mActivity = activity;
   mTag = tag;
   mClass = clz;
   mArgs = args;

   mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
   if (mFragment != null && !mFragment.isDetached()) {
    FragmentTransaction ft = mActivity.getFragmentManager()
      .beginTransaction();
    ft.detach(mFragment);
    ft.commit();
   }
  }

  public void onTabSelected(Tab tab, FragmentTransaction ft) {
   if (mFragment == null) {
    mFragment = Fragment.instantiate(mActivity, mClass.getName(),
      mArgs);
    ft.add(android.R.id.content, mFragment, mTag);
   } else {
    ft.attach(mFragment);
   }
  }

  public void onTabUnselected(Tab tab, FragmentTransaction ft) {
   if (mFragment != null) {
    ft.detach(mFragment);
   }
  }

  public void onTabReselected(Tab tab, FragmentTransaction ft) {
   new CustomToast(mActivity, "Reselected!");
  }
 }
}


Following program creates the first Fragment.
FragmentCalculate.java

package com.example.fragmentexample;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class FragmentCalculate extends Activity {
 int i = 1;

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

  if (savedInstanceState == null) {
   Fragment newFragment = SimpleAddition.newInstance(i);
   FragmentTransaction ft = getFragmentManager().beginTransaction();
   ft.add(R.id.FrameLayout1, newFragment).commit();
  } else {
   i = savedInstanceState.getInt("level");
  }
 }

 @Override
 public void onSaveInstanceState(Bundle outState) {
  super.onSaveInstanceState(outState);
  outState.putInt("level", i);
 }

 public static class SimpleAddition extends Fragment {
  int mNum;

  static SimpleAddition newInstance(int num) {
   SimpleAddition f = new SimpleAddition();

   Bundle args = new Bundle();
   args.putInt("num", num);
   f.setArguments(args);

   return f;
  }
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   mNum = getArguments() != null ? getArguments().getInt("num") : 1;
  }
  
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
   View v = inflater.inflate(R.layout.addition, container, false);
   
   Button b = (Button) v.findViewById(R.id.button1);
   final EditText et1 = (EditText) v.findViewById(R.id.editText1);
   final EditText et2 = (EditText) v.findViewById(R.id.editText2);
   final TextView tv = (TextView) v.findViewById(R.id.textView1);

   b.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
     int a = Integer.parseInt(et1.getText().toString());
     int b = Integer.parseInt(et2.getText().toString());
     tv.setText("  Total = "+String.valueOf(a+b));
    }
   });
   
   return v;
  }
 }

}



Following program creates the second Fragment.
FragmentCalculate.java

package com.example.fragmentexample;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SampleList extends Activity {

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

  FragmentManager fm = getFragmentManager();

  if (fm.findFragmentById(android.R.id.content) == null) {
   SampleListFragment list = new SampleListFragment();
   fm.beginTransaction().add(android.R.id.content, list).commit();
  }
 }

 public static class SampleListFragment extends ListFragment
 {

  String[] numbers_text = new String[] { "one", "two", "three", "four",
    "five", "six", "seven", "eight", "nine", "ten", "eleven",
    "twelve", "thirteen", "fourteen", "fifteen" };
  String[] numbers_digits = new String[] { "1", "2", "3", "4", "5", "6", "7",
    "8", "9", "10", "11", "12", "13", "14", "15" };

  @Override
  public void onListItemClick(ListView l, View v, int position, long id) {
   new CustomToast(getActivity(), numbers_digits[(int) id]);   
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
   ArrayAdapter<String> adapter = new ArrayAdapter<String>(
     inflater.getContext(), android.R.layout.simple_list_item_1,
     numbers_text);
   setListAdapter(adapter);
   return super.onCreateView(inflater, container, savedInstanceState);
  }
 }
}


Layout design for first child.
addition.xml

<?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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ADD" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>


Layout which contains FrameLayout1
addition.xml

<?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:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="4dip" >

    <FrameLayout
        android:id="@+id/FrameLayout1"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1" >
    </FrameLayout>

</LinearLayout>


Source code on GITHUB

1.ListFragments in Android with simple example

2.Simple Fragment Example in Android

3. Simple ListFragment Example in Android

Just have a look on here to CustomToast. This CustomToast is created by using Dialog class in android.

I hope this post is useful to you. kindly share your feedback as comment here.



Thank You



Comments

Post a Comment

Popular posts from this blog

Simple example of OCRReader in Android.

Hi Friends, Maybe you all heard/used text scanning using camera feature or extracting text from Image. But this sample made it very easy for you. You can made it in very simple line of code. You can download the source code from OCRSample and import the library as a module into your project. Example usage : MainActivity.java public class MainActivity extends AppCompatActivity { private TextView textView; private final int CAMERA_SCAN_TEXT = 0; private final int LOAD_IMAGE_RESULTS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSele

Simple example of using Spinner in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Spinner in Android. In Kotlin we don't need to declare and initialize Spinner. We can simply access the id of Spinner from xml. Ex : import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import android.widget.Toast.LENGTH_LONG import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //String array. val myStrings = arrayOf("One", "Two", "Three", "Four", "Five") //Adapter for spinner mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_i

Set limit for fraction in decimal numbers in EditText

            Already we know that we can set which type of input the edittext should accept from user using android:inputType="numberDecimal" But there is no predefined function to set the limit for the edittext to How many digit it should accept after the decimal point from user . We can achieve this by using TextWatcher . Full code example. Following program creates a Decimal Filter. DecimalFilter.java import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import android.widget.EditText; public class DecimalFilter implements TextWatcher { int count= -1 ; EditText et; Activity activity; public DecimalFilter(EditText edittext, Activity activity) { et = edittext; this.activity = activity; } public void afterTextChanged(Editable s) { if (s.length() > 0) { String str = et.getText().toString(); et.setOnKeyListener(new OnKeyL