Wednesday, 31 July 2013

Simple ListFragment Example in Android

This post will help you to create simple ListFragment in android.

MainActivity.java

package com.example.listfragmentexample;

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

public class MainActivity extends Activity {

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

  FragmentManager fm = getFragmentManager();

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

 public static class SimpleListFragment 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);
  }
 }
}


Screen Shot:



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

1. Simple Fragments with Action Bar Example in Android

2. ListFragments in Android with simple example

3. Simple Fragment Example in Android

4. Simple RecyclerView Example in Android



Thank You



Simple Fragment Example in Android

This post will help you to create simple Fragment in android.

MainActivity.java

package com.simple.sfragmentexample;

import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
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 MainActivity extends Activity {
 int i = 1;

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

  setContentView(R.layout.fragment_simple);
  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.activity_main, container, false);
   
   Button b = (Button) v.findViewById(R.id.button1);
   final EditText et1 = (EditText) v.findViewById(R.id.editText1);   
   final TextView tv = (TextView) v.findViewById(R.id.textView1);

   b.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {        
     tv.setText(et1.getText().toString());
    }
   });   
   return v;
  }
 }

}


fragment_simple.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>


activity_main.xml

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

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

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="22dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="28dp"
        android:text="Button" />

</RelativeLayout>


Screen Shot:



1. Simple Fragments with Action Bar Example in Android

2. ListFragments in Android with simple example

3. Simple ListFragment Example in Android

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



Thank You



Sunday, 14 July 2013

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



Tuesday, 2 July 2013

Change spinner text color by button click

We can change the color of spinner text by click the button. Following four steps will explain it clearly.
1. Create a xml named spinnertext.xml in res/layout folder. Here we customize the text of spinner.

spinnertext.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/spinnerText"
    style="?android:attr/spinnerItemStyle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:paddingBottom="2dp"
    android:paddingLeft="6dp"
    android:textColor="#662293" />

2. Create a xml named spinner_selector.xml in res/layout folder. Here we customize the spinner drop down menu.

spinner_selector.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    style="?android:attr/spinnerItemStyle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textColor="#000000" />

3. Now main.xml. Here I get the togglebutton to change the color.

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToggleButton" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

4. Now in code we can work with toggle button to change the color.

code for toggle buttton
ToggleButton mToggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
   mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

       @Override
       public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
           TextView tv = (TextView) findViewById(R.id.spinnerText);
           if (isChecked)
               tv.setTextColor(Color.BLUE);
           else
               tv.setTextColor(Color.RED);

       }
});

code for spinner adapter
String array[] = { "one", "two", "three" };
ArrayAdapter sp_adapter = new ArrayAdapter(this, R.layout.spinnertext, array);
sp_adapter.setDropDownViewResource(R.layout.spinner_selector);
Spinner sp = (Spinner) findViewById(R.id.spinner1);
sp.setAdapter(sp_adapter);


complete code
SpinnerTextActivity.java
package com.example.spinnertext;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;

public class SpinnerTextActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ToggleButton mToggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
        mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
                TextView tv = (TextView) findViewById(R.id.spinnerText);
                if (isChecked)
                    tv.setTextColor(Color.BLUE);
                else
                    tv.setTextColor(Color.RED);

            }
        });
        
        String array[] = { "one", "two", "three" };
        ArrayAdapter<String> sp_adapter = new ArrayAdapter<String>(this, R.layout.spinnertext, array);
        sp_adapter.setDropDownViewResource
        (R.layout.spinner_selector);
        Spinner sp = (Spinner) findViewById(R.id.spinner1);
        sp.setAdapter(sp_adapter);
    }
}


Screen shot 1. (ToggleButton is ON)



Screen shot 2. (ToggleButton is OFF)



Thank You