Saturday, 20 June 2015

Easiest Android Fragments Tutorial


In this tutorial, we will go through the following topics

  • What is a Fragment?
  • Why should we go for Fragment?
  • Different Approaches for creating a Fragment
What is a Fragment ?

  • A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity.
  • A Fragment enables more modular Activity design. Its a kind of Sub-Activity.It has its own LifeCycle.
  • A Fragment represents a portion of a user interface or an operation that runs within an Activity.
Why should we go for Fragment?
  • The main reason why one should go for Fragments is  the convenience of reusing the components in different layouts. 
  • With the fragments we have more flexibility and can remove the limitation of having a single activity on the screen at a time. 
  • Now we can have a single activity but each activity can comprise of multiple fragments which will have their own layout, events and complete life cycle.

Different Approaches for creating a Fragment:

There are 2 different approaches for calling a Fragment from an Activity.
  1. Calling it from Activity's XML [Layout]
  2. Calling it from Java code [MainActivity]


Type 1: Creating a Fragment and Calling it from Activitys XML Layout

1.1 Create a Layout for the Fragment.

<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="wrap_content"    // Height is given as wrap_content so as to distinguish between Fragment and Acivity
    android:background="#00bbff"                // To distinguish between Fragment and Acivity
    tools:context="in.blogspot.easyandroidtutorial.workouts.FirstFragment">

    <TextView
        android:padding="70dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

1.2 Create your FirstFragment class that extends Fragment class.

package in.blogspot.easyandroidtutorial.workouts;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FirstFragment extends Fragment {

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

package in.blogspot.easyandroidtutorial.workouts;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MyActivity extends Activity {

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

1.4 Modify your MainAcivity's layout to call the fragment created in 1.1

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:id="@+id/myact"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="#ffbb00"    // To distinguish between Fragment and Acivity
    tools:context="in.blogspot.easyandroidtutorial.workouts.MyActivity">

    <fragment
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:name="in.blogspot.easyandroidtutorial.workouts.FirstFragment"
        android:id="@+id/fragment"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>





Type 2: Creating a Fragment and Calling it from MainActivity's Java code  

Here the Steps 1.1, 1.2 are same.

2.3 Create your MainActivity's Layout

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:id="@+id/myact"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="#ffbb00"
    tools:context="in.blogspot.easyandroidtutorial.workouts.MyActivity">

</RelativeLayout>

2.4 Modify your MainActivity to call your FirstFragment

package in.blogspot.easyandroidtutorial.workouts;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MyActivity extends Activity {

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

       // Getting the FragmentManager instance associated with this class
        FragmentManager fm = getFragmentManager(); 
        FragmentTransaction ft = fm.beginTransaction();

        FirstFragment firstFragment = new FirstFragment();

      // Add the FirstFragment instance to your MainActivitys Layout
        ft.add(R.id.myact, firstFragment);

        ft.commit();
    }

That's it. Done. 

Output:






Your comments on this tutorial are most Welcome. Please help improving this blog by your valuable comments. Thanks. Happy Coding




Wednesday, 17 June 2015

Easiest RecyclerView Example

RecyclerView ?

The RecyclerView is a new ViewGroup  similar to and much more than a LisView.
It is supossed to be the successor of ListView and GridView with Material Design Style.
It can be found in the latest support-v7 version.

How to use RecyclerView ?

The 2 mandatory elements require to create a RecyclerView are.

–Your Adapter that extends RecyclerView.Adapter and implements your ViewHolder
– LayoutManager [Default layout manager -LinearLayoutManager.]


Note: Your ViewHolder class is a simple class with a constructor to find the views in your layout.

Step 1: Add dependency in your build.gradle

dependencies {
    
    compile 'com.android.support:recyclerview-v7:21.0.+'
}

Step 2: Add RecyclerView in Layout 

<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"
    tools:context=".MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</LinearLayout>


Step 3:  Design your RowView

<?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">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:id="@+id/list_item"
        xmlns:android="http://schemas.android.com/apk/res/android" />


</LinearLayout>

Step 4: Create your Adapter for RecyclerView. and your ViewHolder class

The new RecyclerView.Adapter abstract/generic class is similar in behavior to the old BaseAdapter. There are 3  methods you need to implement:

onCreateViewHolder – It creates the ViewHolder for speciic row display.It inflates the row layout for the row and creates a ViewHolder with that layout.

onBindViewHolder – It updates the row’s View components with data from the dataset.Called by the RecyclerView when it needs to display the data at the position/row specified as a parameter.

getItemCount – It returns the number of rows in the associated data set.

Code:

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    private String[] dataSource;
    public RecyclerAdapter(String[] dataArgs){
        dataSource = dataArgs;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.textView.setText(dataSource[position]);
    }

    @Override
    public int getItemCount() {
        return dataSource.length;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        public TextView textView;
        public ViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView;
        }
    }
}

Step 5: Modify your MainAcivity to use the RecyclerView

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public class MainActivity extends Activity {
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    String[] dataArray = new String[]{"JellyBean","KitKat","Lollipop"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RecyclerAdapter(dataArray);
        recyclerView.setAdapter(adapter);
    }
}


OutPut:





Another excellent tutorial on RecyclerView is available at

https://www.binpress.com/tutorial/android-l-recyclerview-and-cardview-tutorial/156

http://www.vogella.com/tutorials/AndroidRecyclerView/article.html

http://blog.lovelyhq.com/creating-lists-with-recyclerview-in-android/

Monday, 8 June 2015

Easiest ListView Example

This is a simplest Android Example for Android ListView

Introduction:

Android ListView is a view group that displays a list of scrollable items.

Android provides ListView and ExpandableListView classes for displaying scrollable list of items.

Note 1: When creating your main activity , you can extend ListActivity to use the default ListView but make sure you declare it as,

<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/mainText"
android:id="@android:id/list"


Also, you can assign the list adapter as

setListAdapter(myAdapter);

Thats the only difference.

Note 2: Important: Though you have a  ArrayList of Strings as source for listview, whenever you use the ArrayAdapter it should be declared as ArrayAdapter<String>

Adapter:
An adapter manages the data model and adapts it to the individual entries in the widget. An adapter extends the BaseAdapter class.

Default Adapters:
Android provides default adapter implementations; the most important are ArrayAdapter and CursorAdapter. ArrayAdapter can handle data based on Arrays or java.util.List. SimpleCursorAdapter can handle database related data.


Step 1 : Create a layout file with ListView
Step 2 : In your Activity, access the ListView created in Step 1 and perform the possible desired actions


  • Get ListView object from xml
  • Defined Array values to show in ListView
  • Define a new Adapter
  • Assign adapter to ListView
  • Implement ListView Item Click Listener





Step 1 : Create a layout file with ListView

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

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listview1"></ListView>

</RelativeLayout>




Step 2 :  In your Activity, access the ListView created in Step 1 and perform the possible desired actions.


public class MyListView extends Activity {
    ListView lv;

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

        lv = (ListView)findViewById(R.id.listview1);     // Get ListView object from xml

        String values[] = {"Jellybean","Kitkat","Lollipop"};  // Defined Array values to show in ListView

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1,values);   // Define a new Adapter

        lv.setAdapter(adapter);  // Assign adapter to ListView

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {    //Implement ListView Item Click Listener
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int position = i;

                String x = (String)lv.getItemAtPosition(i);

                Toast.makeText(getApplicationContext(),"the selected item is " +x+" and at postion "+position, Toast.LENGTH_LONG).show();;
            }
        });

    }



OutPut : 










Excellent Tutorial on Customized Adapter is available in 

http://www.codelearn.org/android-tutorial/android-listview