Sunday, October 16, 2016

Android Custom Spinner Item Example

Sometimes you need to display dropdown spinner item with complex item consists not only string text, but with icon beside it. For example a dropdown spinner like the picture below showing a country list and its flag beside it.

Custom spinner showing text and image

Just follow the steps below to make that custom spinner.

1. Make activity layout file activity_spinner.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="12dp">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">

    </Spinner>

</RelativeLayout>
2. Make item layout  file item_country.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:padding="12dp">

    <ImageView
        android:id="@+id/imgFlag"
        android:layout_width="32dp"
        android:layout_height="32dp" />
    <TextView
        android:id="@+id/textCountry"
        android:layout_marginLeft="4dp"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

</LinearLayout>
3. Make country class Country.java
package com.example.myapplication.spinner;

/**
 * Created by SONY on 16/10/2016.
 */
public class Country {
    public String name;
    public int flag;
}

4. Make custom spinner adapter class CustomSpinnerAdapter.java
package com.example.myapplication.spinner;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.myapplication.R;

import java.util.List;

/**
 * Created by SONY on 16/10/2016.
 */
public class CustomSpinnerAdapter extends ArrayAdapter<Country> {
    private List<Country> data;
    public CustomSpinnerAdapter(Context context, List<Country> data) {
        super(context, 0, data);
        this.data = data;
    }
    @Override
    public View getDropDownView(int position, View convertView,ViewGroup parent) {
        return getView(position, convertView, parent);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        Country country = data.get(position);
        if(convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_country, parent, false);
            convertView.setTag(ViewHolder.createViewHolder(convertView));
        }
        ViewHolder holder = (ViewHolder)convertView.getTag();
        holder.textCountry.setText(country.name);
        holder.imgFlag.setImageResource(country.flag);
        return convertView;
    }
    @Override
    public int getCount( ) {
        return data.size();
    }

    private static class ViewHolder {
        public ImageView imgFlag;
        public TextView textCountry;

        public static ViewHolder createViewHolder(View view) {
            ViewHolder holder = new ViewHolder();
            holder.imgFlag = (ImageView) view.findViewById(R.id.imgFlag);
            holder.textCountry = (TextView)view.findViewById(R.id.textCountry);
            return holder;
        }
    }
}

5. Paste these png images into drawable folder
flag_china.png
flag_germany.png
flag_india.png
flag_indonesia.png
flag_usa.png


6. Make activity class SpinnerActivity.java

package com.example.myapplication.spinner;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;

import com.example.myapplication.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by SONY on 16/10/2016.
 */
public class SpinnerActivity extends Activity {
    private Spinner spinner;
    private CustomSpinnerAdapter spinnerAdapter;
    private List<Country> countries = new ArrayList<Country>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner);
        spinner = (Spinner) findViewById(R.id.spinner);
        spinnerAdapter = new CustomSpinnerAdapter(this, countries );
        spinner.setAdapter(spinnerAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // do something after selected item here
                Country country = countries.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        populateCountries();
    }
    private void populateCountries() {
        Country indonesia = new Country();
        indonesia.name = "Indonesia";
        indonesia.flag = R.drawable.flag_indonesia;
        Country usa = new Country();
        usa.name = "United States";
        usa.flag = R.drawable.flag_usa;
        Country germany = new Country();
        germany.name = "Germany";
        germany.flag = R.drawable.flag_germany;
        Country china = new Country();
        china.name = "China";
        china.flag = R.drawable.flag_china;
        Country india = new Country();
        india.name = "India";
        india.flag = R.drawable.flag_india;
        countries.add(indonesia);
        countries.add(usa);
        countries.add(germany);
        countries.add(china);
        countries.add(india);
        spinnerAdapter.notifyDataSetChanged();
    }
}

7. Make AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name="com.example.myapplication.spinner.SpinnerActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
8. Now run the app. You should see a spinner showing country list with name and flag like in the picture above.

 Thank you for visiting our website. Just comment below if you have any question to ask.

Saturday, October 15, 2016

Android Simple Spinner Example

Android spinner is used to display a drop down list to be selected by user. To make android spinner working, just follow these simple steps.


1. Create activity layout activity_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="12dp">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">

    </Spinner>

</RelativeLayout>
2. Copy and paste array of string below to strings.xml file inside values folder.
<string-array name="month_array">
        <item>January</item>
        <item>Febuary</item>
        <item>March</item>
        <item>April</item>
        <item>May</item>
        <item>June</item>
        <item>July</item>
        <item>August</item>
        <item>September</item>
        <item>October</item>
        <item>November</item>
        <item>December</item>
 </string-array>
3. Make activity class SpinnerActivity.java
package com.example.myapplication.spinner;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.example.myapplication.R;

/**
 * Created by SONY on 16/10/2016.
 */
public class SpinnerActivity extends Activity {
    private Spinner spinner;
    private ArrayAdapter<CharSequence> spinnerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner);
        spinner = (Spinner) findViewById(R.id.spinner);
        spinnerAdapter = ArrayAdapter.createFromResource(this,
                R.array.month_array, android.R.layout.simple_spinner_item);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spinnerAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // do something after selected item here
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}

4. Make AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name="com.example.myapplication.spinner.SpinnerActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
5. After you run the application and click the spinner, it should display the dropdown item like the picture below.


Thank you for visiting our website. Just comment below if you have any question to ask.

Android Gravity Example

When making a layout in android you frequently find xml attribute android:gravity. To understand what is this gravity means, I will give you an example. First look at the layout design in the picture below that is generated by xml without adding android:gravity attribute.

with no android:gravity attribute the layout is put on top.
Now look at the xml code that generate that layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Login"
        android:layout_weight="1"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Signup"
        android:layout_weight="1"/>


</LinearLayout>
Now let's put xml attribute android:gravity="center" inside LinearLayout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Login"
        android:layout_weight="1"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Signup"
        android:layout_weight="1"/>


</LinearLayout>


Below is the result after we add android:gravity="center" to LinearLayout



From the above picture you can see that android:gravity="center" moves all of LinearLayout's children (Login and Signup button) the center of the screen.

Thank you for visiting our website. Just comment below if you have any question to ask.

Android LinearLayout vs RelativeLayout

In Android development you frequently hear about LinearLayout and RelativeLayout but still confuse what are the differents. Both are different in the way they put the children components inside them.
To give you example about this, let's try to make a login page like in the picture below. Because this login page has many components such as EditText and Button ,  these components can be put inside both LinearLayout and RelativeLayout. Only the technique they use in ordering its components is different between LinearLayout and RelativeLayout.




1. Now let's make that login page using LinearLayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="match_parent"
    android:padding="12dp"
    android:layout_height="match_parent">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Email"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"/>

</LinearLayout>
2. Now let's make that login page using RelativeLayout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="12dp">

    <EditText
        android:id="@+id/editEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Email"/>
    <EditText
        android:id="@+id/editPassword"
        android:layout_below="@+id/editEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editPassword"
        android:text="Login"/>

</RelativeLayout>
We can see that in LinearLayout we don't need to specify explicitly that password' EditText should be put below Email's EditText because we have set the orientation as vertical so each component will be put below previous component. But in RelativeLayout we should explicitly tell the password' EditText to be put below Email's EditText by using xml code android:layout_below="@+id/editEmail", if we don't use this xml code the password' EditText will be put on top overlap the Email's EditText. RelativeLayout is more efficient to be used rather than LinearLayout that consumes a lot of performance. But LinearLayout has some advantages in some cases, for example if you need to divide or split a screen in two equally you can use easily with LinearLayout rather than RelativeLayout. For example if you need to make two buttons with equal size that will fill the entire screen horizontally like in the picture below.
Use LinearLayout like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Login"
        android:layout_weight="1"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Signup"
        android:layout_weight="1"/>


</LinearLayout>
After you run the app, try to rotate your android phone from portrait to landscape. In landscape orientation, the two buttons still in equal size and fill the entire screen horizontally. This is not easy if you use RelativeLayout rather than LinearLayout.

Thank you for visiting our website. Just comment below if you have any question to ask.

Android Alert Dialog Example

In this tutorial I will show you how to generate alert dialog in android. If you follow the steps below you will see that it is very easy to do that. Just follow my example below.

1. Create layout activity xml to host the alert dialog, name it activity_show_alert.xml and put under layout folder.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <Button
        android:id="@+id/btnShowAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="Show Alert"/>

</RelativeLayout>

2. Create activity class, name it ShowAlertActivity.java
package com.example.myapplication.alert;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.example.myapplication.R;

/**
 * Created by SONY on 15/10/2016.
 */
public class ShowAlertActivity extends Activity {
    private Button btnShowAlert;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_alert);

        btnShowAlert = (Button) findViewById(R.id.btnShowAlert);
        btnShowAlert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAlertDialog();
            }
        });
    }
    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose yes or no");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }
}
3. Create AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name="com.example.myapplication.alert.ShowAlertActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
4. Run application it will show page like the picture below.
5. Click show alert button it will display an alert dialog like in the picture below.
Thank you for visiting our website. Just comment below if you have any question to ask.

Friday, October 14, 2016

Android Listview Multiple item type example

If you want to make a listview with different type of item for example to show a list of students with a label header based on their faculty follow these simple steps :


1.  Create a layout activity with name activity_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</ListView>

2. Insert this png icon into drawable folder. name it ic_picture.png
3. Create item layout to represent a student, name it item_student.xml
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:padding="16dp"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgStudent"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:scaleType="centerCrop"/>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <TextView
            android:id="@+id/textName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/textID"
            android:layout_below="@+id/textName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </RelativeLayout>

</LinearLayout>

4. Create item header layout, name it item_header.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    android:padding="12dp">
    <TextView
        android:id="@+id/textHeader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="16sp"
        android:textStyle="bold"
        android:textColor="#ffffff"
        android:gravity="center"/>

</RelativeLayout>
5. Create BaseItem.java class
package com.example.myapplication.customarray;

/**
 * Created by SONY on 15/10/2016.
 */
public class BaseItem {
    
    public int type;
}


6. Create StudentItem.java class that extends BaseItem.java
package com.example.myapplication.customarray;

/**
 * Created by SONY on 14/10/2016.
 */
public class StudentItem extends BaseItem {
    public String name;
    public String id;
    public int picture;

}
7. Create HeaderItem.java class that extends BaseItem.java
package com.example.myapplication.customarray;

/**
 * Created by SONY on 15/10/2016.
 */
public class HeaderItem extends BaseItem {

    public String label;
}

8. Create CustomAdapter.java class
package com.example.myapplication.customarray;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.myapplication.R;
import java.util.List;

/**
 * Created by SONY on 14/10/2016.
 */
public class CustomAdapter extends ArrayAdapter<BaseItem> {

    private List<BaseItem> data;

    public CustomAdapter(Context context, List<BaseItem> data) {
        super(context, 0, data);
        this.data = data;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        BaseItem baseItem = data.get(position);
        if(convertView == null) {
            if(baseItem.type == 0) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_student, parent, false);
                convertView.setTag(ViewHolder.createHolder(convertView));
            }
            else {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_header, parent, false);
                convertView.setTag(ViewHolderHeader.createViewHolder(convertView));
            }
        }
        if(baseItem.type == 0) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            StudentItem student = (StudentItem) data.get(position);
            holder.textName.setText(student.name);
            holder.textID.setText(student.id);
            holder.imgStudent.setImageResource(student.picture);
        }
        else {
            ViewHolderHeader holderHeader = (ViewHolderHeader) convertView.getTag();
            HeaderItem headerItem = (HeaderItem) data.get(position);
            holderHeader.textLabel.setText(headerItem.label);
        }
       return convertView;
    }

    @Override
    public int getCount( ) {
        return data.size();
    }
    @Override
    public int getViewTypeCount() {
        return 2;
    }
    @Override
    public int getItemViewType(int position) {
        BaseItem item = data.get(position);
        return item.type;
    }



    public static class ViewHolder  {
        public TextView textName;
        public TextView textID;
        public ImageView imgStudent;

        public static final ViewHolder createHolder(View view) {
            ViewHolder holder = new ViewHolder();
            holder.textName = (TextView) view.findViewById(R.id.textName);
            holder.textID = (TextView) view.findViewById(R.id.textID);
            holder.imgStudent = (ImageView) view.findViewById(R.id.imgStudent);
            return holder;
        }
    }
    public static class ViewHolderHeader {
        public TextView textLabel;

        public static final ViewHolderHeader createViewHolder(View view) {
            ViewHolderHeader holderHeader = new ViewHolderHeader();
            holderHeader.textLabel = (TextView)view.findViewById(R.id.textHeader);
            return holderHeader;
        }
    }
}

9. Create CustomActivity.java class
package com.example.myapplication.customarray;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import com.example.myapplication.R;
import java.util.ArrayList;


/**
 * Created by SONY on 14/10/2016.
 */
public class CustomActivity extends Activity {
    private ListView listView;
    private CustomAdapter adapter;
    private ArrayList<BaseItem> data = new ArrayList<BaseItem>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview);
        listView = (ListView) findViewById(R.id.listView);
        adapter = new CustomAdapter(this, data);
        listView.setAdapter(adapter);
        populateListView();
    }

    private void populateListView() {
        HeaderItem headerItem1 = new HeaderItem();
        headerItem1.type = 1;
        headerItem1.label = "Engineering";

        StudentItem student1 = new StudentItem();
        student1.type = 0;
        student1.name = "Muhammad";
        student1.id = "123455";
        student1.picture = R.drawable.ic_picture;

        StudentItem student2 = new StudentItem();
        student2.type = 0;
        student2.name = "Ali";
        student2.id = "123456";
        student2.picture = R.drawable.ic_picture;

        StudentItem student3 = new StudentItem();
        student3.type = 0;
        student3.name = "Rahman";
        student3.id = "123457";
        student3.picture = R.drawable.ic_picture;

        HeaderItem headerItem2 = new HeaderItem();
        headerItem2.type = 1;
        headerItem2.label = "Medicine";

        StudentItem student4 = new StudentItem();
        student4.type = 0;
        student4.name = "David";
        student4.id = "123458";
        student4.picture = R.drawable.ic_picture;

        StudentItem student5 = new StudentItem();
        student5.type = 0;
        student5.name = "Roberts";
        student5.id = "123459";
        student5.picture = R.drawable.ic_picture;

        StudentItem student6 = new StudentItem();
        student6.type = 0;
        student6.name = "Ismail";
        student6.id = "123451";
        student6.picture = R.drawable.ic_picture;
        data.add(headerItem1);
        data.add(student1);
        data.add(student2);
        data.add(student3);
        data.add(headerItem2);
        data.add(student4);
        data.add(student5);
        data.add(student6);
        adapter.notifyDataSetChanged();

    }
}

10. Create AndroidManifest.xml file. Warning: adjust your activity package name in line <activity android:name=<your_activity_package>>. If your package name is not correct the app will crash at run time.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".customarray.CustomActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
11. After you run your application you should see the screen like this. notice label item is shown now (Engineering and Medicine).
Thank you for visiting our website. Just comment below if you have any question to ask.

Android Listview custom array adapter example

With custom array adapter you can create listview with complex list item not just only string item.
for example if you have to show a list of students with  name, id, and picture. you can use
custom array adapter. Below are the steps to follow :

1. Create an activity layout with name activity_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</ListView>
2. Create an item layout to show student item with name item_student.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:padding="16dp"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgStudent"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:scaleType="centerCrop"/>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <TextView
            android:id="@+id/textName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/textID"
            android:layout_below="@+id/textName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </RelativeLayout>

</LinearLayout>
3. create a student class with name Student.java
package com.example.myapplication.customarray;

/**
 * Created by SONY on 14/10/2016.
 */
public class Student {
    public String name;
    public String id;
    public int picture;

}
4. Create a custom array adapter class with name CustomAdapter.java
package com.example.myapplication.customarray;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.myapplication.R;
import java.util.List;

/**
 * Created by SONY on 14/10/2016.
 */
public class CustomAdapter extends ArrayAdapter<Student> {

    private List<Student> students;

    public CustomAdapter(Context context, List<Student> students) {
        super(context, 0, students);
        this.students = students;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        if(convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_student, parent, false);
            convertView.setTag(ViewHolder.createHolder(convertView));
        }
        ViewHolder holder = (ViewHolder) convertView.getTag();
        Student student = students.get(position);
        holder.textName.setText(student.name);
        holder.textID.setText(student.id);
        holder.imgStudent.setImageResource(student.picture);
       return convertView;
    }

    @Override
    public int getCount( ) {
        return students.size();
    }


    public static class ViewHolder  {
        public TextView textName;
        public TextView textID;
        public ImageView imgStudent;

        public static final ViewHolder createHolder(View view) {
            ViewHolder holder = new ViewHolder();
            holder.textName = (TextView) view.findViewById(R.id.textName);
            holder.textID = (TextView) view.findViewById(R.id.textID);
            holder.imgStudent = (ImageView) view.findViewById(R.id.imgStudent);
            return holder;
        }
    }
}


5. Copy paste the image below to drawable folder with name ic_picture.png
6. Create activity class with name CustomActivity.java
package com.example.myapplication.customarray;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import com.example.myapplication.R;
import java.util.ArrayList;


/**
 * Created by SONY on 14/10/2016.
 */
public class CustomActivity extends Activity {
    private ListView listView;
    private CustomAdapter adapter;
    private ArrayList<Student> data = new ArrayList<Student>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview);
        listView = (ListView) findViewById(R.id.listView);
        adapter = new CustomAdapter(this, data);
        listView.setAdapter(adapter);
        populateListView();
    }

    private void populateListView() {
        Student student1 = new Student();
        student1.name = "Muhammad";
        student1.id = "123455";
        student1.picture = R.drawable.ic_picture;

        Student student2 = new Student();
        student2.name = "Ali";
        student2.id = "123456";
        student2.picture = R.drawable.ic_picture;

        Student student3 = new Student();
        student3.name = "Rahman";
        student3.id = "123457";
        student3.picture = R.drawable.ic_picture;

        Student student4 = new Student();
        student4.name = "David";
        student4.id = "123458";
        student4.picture = R.drawable.ic_picture;

        Student student5 = new Student();
        student5.name = "Roberts";
        student5.id = "123459";
        student5.picture = R.drawable.ic_picture;

        Student student6 = new Student();
        student6.name = "Ismail";
        student6.id = "123451";
        student6.picture = R.drawable.ic_picture;

        data.add(student1);
        data.add(student2);
        data.add(student3);
        data.add(student4);
        data.add(student5);
        data.add(student6);
        adapter.notifyDataSetChanged();

    }
}

6. Create AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".customarray.CustomActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
7. After you run the app, you should see the result like this.
Thank you for visiting our website. Just comment below if you have any question to ask.