ListFragment Event Handling using onListItemClick

September 05, 2013

ScreenShots:

   
After click's the item  :

MonthsListFragment:

package com.ram.listfragmen;

import android.annotation.SuppressLint;
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;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MonthsListFragment extends ListFragment {
    String[] MONTHS = { "jan", "feb", "march", "april", "may", "june", "july",
            "august", "sep", "octo", "nov", "dec" };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                inflater.getContext(), android.R.layout.simple_list_item_1,
                MONTHS);

        setListAdapter(adapter);

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);

        Toast.makeText(getActivity(), "selected month :" + MONTHS[position],
                Toast.LENGTH_LONG).show();
    }

}

MainActivity.java:

package com.ram.listfragmen;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

}
 

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >

    <fragment
        android:id="@+id/fragment1"
        android:name="com.ram.listfragmen.MonthsListFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>




Artikel Terkait

Previous
Next Post »