Pages

Thursday, June 2, 2016

List Fragment Event Handling using onListItemClick

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="in.blogspot.kantapp.listfragmenteventhandlingusingonlistitemclick.MonthsListFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/simple_list_item_1" />

</LinearLayout>
MainActivity.java
package in.blogspot.kantapp.listfragmenteventhandlingusingonlistitemclick;

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);
    }

}
MonthsListFragment.java
package in.blogspot.kantapp.listfragmenteventhandlingusingonlistitemclick;

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();
    }

}

No comments:

Post a Comment