ListDialog for Each Items of ListView and Deleting RowItems

By | June 8, 2014

In the previous tutorial we have already seen an example of Dialog Fragment Containing a List View which is shown on click of a button , here in this tutorial i am extending this concept to show the list dialog fragment on long item click of a list view , and we also see how to delete a row items of a list view by prompting a alert dialog to user for confirming deletion .

Below is the screenshot of the application .

String Constant

Before i start coding i am initializing items of list view in string-array .

file : strings.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<resources>

    <string name=”app_name”>ListViewWithDialog</string>
    <string name=”action_settings”>Settings</string>
    <string name=”hello_world”>Hello world!</string>

    <!– ListView Item Names –>
    <string-array name=”list_items”>
        <item>List_Item_01</item>
        <item>List_Item_02</item>
        <item>List_Item_03</item>
        <item>List_Item_04</item>
        <item>List_Item_05</item>
        <item>List_Item_06</item>
        <item>List_Item_07</item>
        <item>List_Item_08</item>
        <item>List_Item_09</item>
        <item>List_Item_10</item>
    </string-array>

    <!– Dialog List Items –>
    <string-array name=”dialog_items”>
        <item>Show Item Position</item>
        <item>Show Item Name</item>
        <item>Delete Item</item>
    </string-array>

</resources>

XML Layout

Create Two XML Layout , one for main activity and another for the which is shown as dialog.

  1. activity_main.xml .
  2. dialog_fragment.xml.

file : activity_main.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” >

    <ListView
        android:id=”@+id/mylist”
        android:layout_width=”match_parent”
        android:layout_height=”wrap_content” >
    </ListView>

</LinearLayout>

file :dialog_fragment.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout
    xmlns:android=”http://schemas.android.com/apk/res/android”
    android:layout_width=”fill_parent”
    android:layout_height=”fill_parent”
    android:layout_marginLeft=”5dp”
    android:layout_marginRight=”5dp” >

    <ListView
        android:id=”@+id/dialog_list”
        android:layout_width=”match_parent”
        android:layout_height=”match_parent”
        android:layout_marginLeft=”10dp”
        android:layout_marginRight=”10dp” >
    </ListView>

</LinearLayout>

Dialog Fragment

I have already discussed about how to create dialog fragment containing in my previous tutorial , you can refer and come back .

Here i am setting the onItemClick Listener for items of list view of dialog and inside this listener i am using the concept of inter fragment communication ( which i discussed at fragment tutorial page )  , so inside this listener i am invoking a message( int ) by passing item position clicked .  

file :MyDialogFragment.java

package com.example.listviewwithdialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

@SuppressLint(“NewApi”)
public class MyDialogFragment extends DialogFragment implements
        OnItemClickListener {

    ListView mylist;
    Communicator communicator;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.dialog_fragment, null, false);
        mylist = (ListView) view.findViewById(R.id.dialog_list);

        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        return view;
    }

    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

        if (activity instanceof Communicator) {
            communicator = (Communicator) getActivity();
        } else {
            throw new ClassCastException(activity.toString()
                    + ” must implemenet MyListFragment.communicator”);
        }

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                getActivity(), R.array.dialog_items,
                android.R.layout.simple_list_item_1);

        mylist.setAdapter(adapter);
        mylist.setOnItemClickListener(this);

    }

    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        dismiss();
        communicator.message(position);

    }

    public interface Communicator {
        public void message(int data);
    }

}

Main Activity

Here in the main activity set the content of an activity with the above defined XML(activity_main.xml)  , for the list view set the on ItemLongClick Listener and show the fragment dialog  
 
When the user clicks the items of list view of dialog , a message( int ) method inside main activity  gets called, by determining the item position clicked on item of list dialog , the corresponding task is performed .

Deleting The RowItems Of ListView .

for deleting items of list view call the remove( ) method on adapter object by passing the name of them item which you want to delete .

file :MainActivity.java

package com.example.listviewwithdialog;

import java.util.ArrayList;
import java.util.Arrays;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemLongClickListener,
        MyDialogFragment.Communicator {

    ListView listview;
    ArrayList<String> list_items;
    int item_position_clicked;
    ArrayAdapter<String> adapter;

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

        listview = (ListView) findViewById(R.id.mylist);

        list_items = new ArrayList<String>(Arrays.asList(getResources()
                .getStringArray(R.array.list_items)));

        prepareList();

    }

    private void prepareList() {

        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, list_items);

        listview.setAdapter(adapter);

        adapter.notifyDataSetChanged();

        listview.setOnItemLongClickListener(this);

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,
            int position, long id) {

        item_position_clicked = position;

        android.app.FragmentManager manager = getFragmentManager();

        MyDialogFragment dialog = new MyDialogFragment();
        dialog.show(manager, “dialog”);

        return true;
    }

    @Override
    public void message(int data) {

        switch (data) {
        case 0:
            // Show Item Position
            ToastMsg(“Name :” + item_position_clicked);
            break;
        case 1:
            // Show Item Name
            ToastMsg(“Name :” + list_items.get(item_position_clicked));
            break;

        case 2:
            // Delete Item
            showAlertConfirm();
            break;
        }
    }

    public void showAlertConfirm() {
        final String item_name = list_items.get(item_position_clicked);
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();

        // Setting Dialog Title
        alertDialog.setTitle(“Confirm Delete…”);

        // Setting Dialog Message
        alertDialog.setMessage(“Are you sure you want delete ” + item_name
                + “?”);

        // Setting Positive “Yes” Button
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, “YES”,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                       adapter.remove(list_items.get(item_position_clicked));
                        adapter.notifyDataSetChanged();
                        ToastMsg(item_name + “Deleted”);

                    }
                });

        // Setting Negative “Cancel” Button
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, “Cancel”,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.cancel();
                    }
                });
       
        alertDialog.show();

    }
}

public void ToastMsg(String msg) {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }