How to make a custom dialog with checkbox list like setMultiChoiceItems, receive and send data?

Samanta Silva :

I need to use a dialog like setMultiChoiceItems style but with more information, so I'm using a custom layout.

My layout contains one image field, another title field, another description field, and another one from a checkbox.

enter image description here

I already managed to make it work like this:

enter image description here

I know I need to use a setAdapter instead of setMultiChoiceItems. So far so good.

My problem is how I can open the dialog with some options already selected? And later to receive all selected items to send to the server?

With setMultiChoiceItems I can make it work like this:

enter image description here

But I can not seem to work with the custom layout.

Here is my code:

##### ArrayList - ALItensValues #####

public class ALItensValues {
    private int icon;
    private String value;
    private String titulo;
    private String descricao;

    public ALItensValues(int icon, String value, String titulo, String descricao) {
        this.icon = icon;
        this.value = value;
        this.titulo = titulo;
        this.descricao = descricao;
    }

    int getIcon() { return icon; }
    String getValue() { return value; }
    String getTitulo() { return titulo; }
    String getDescricao() { return descricao; }
}

##### Adapter - ALItensValuesAdapter #####

private class ALItensValuesAdapter extends BaseAdapter {

    private ArrayList<ALItensValues> mData;
    private Context mContext;

    ALItensValuesAdapter(ArrayList<ALItensValues> aldata, Context context) {
        this.mData = aldata;
        this.mContext = context;
    }

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

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = Objects.requireNonNull(mInflater).inflate(R.layout.multipleselectcustom_lines, null);
        }

        ImageView icon = convertView.findViewById(R.id.imgvicon);
        icon.setImageResource(mData.get(position).getIcon());
        TextView titulo = convertView.findViewById(R.id.txtv_titulo);
        titulo.setText(mData.get(position).getTitulo());
        TextView decricao = convertView.findViewById(R.id.txtv_desc);
        decricao.setText(mData.get(position).getDescricao());
        CheckBox checkbox = convertView.findViewById(R.id.chkbox);

        convertView.setOnClickListener(v -> {
            checkbox.toggle();
        });

        return convertView;
    }
}

#### Layout Itens - R.layout.multipleselectcustom_lines ####

<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content" android:gravity="center">

    <ImageView
            android:id="@+id/imgvicon"
            tools:srcCompat="@tools:sample/avatars"
            android:layout_width="wrap_content"
            android:layout_height="60dp"
            android:layout_marginTop="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginBottom="8dp"
            android:adjustViewBounds="true"/>
    <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:layout_weight="1">
        <TextView
                android:text="Titulo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:id="@+id/txtv_titulo"
                android:layout_marginLeft="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginRight="8dp" android:textSize="18sp"/>
        <TextView
                android:text="Descrição"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:id="@+id/txtv_desc"
                android:layout_marginLeft="8dp" android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginRight="8dp" android:visibility="visible" android:layout_marginTop="3dp"/>
    </LinearLayout>
    <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/chkbox"
            android:layout_marginEnd="8dp" android:layout_marginRight="8dp"
            android:layout_marginTop="8dp" android:layout_marginBottom="8dp"
    />
</LinearLayout>

#### Activity Class ####

public class FormsMultipleSelectCustomJava extends AppCompatActivity {

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

// I get the items that should be selected separated by commas.
// And I do the following to transform into array, 
//  but I do not know how to use it in dialog.:

String selectItensServer = "0b2,0e5,0f6,0h8";  
String[] selectInitItens = selectItensServer.split(",");

// List of items that should appear in the dialog.

        ArrayList<ALItensValues> AlertDialogitemList = new ArrayList<>();
        AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_bicycle, "0a1", "Test 1", "Lorem ipsum dolor sit amet"));
        AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_btc, "0b2", "Test 2", "Duis at ullamcorper quam"));
        AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_car, "0c3", "Test 3", "Aenean aliquam sit amet nibh eget bibendum"));
        AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_credit_card, "0d4", "Test 4", "Sed a est vel velit rutrum porta"));
        AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_gamepad, "0e5", "Test 5", "Phasellus pellentesque arcu et fermentum tempus"));
        AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_gift, "0f6", "Test 6", "Integer arcu leo, consequat eget tempus sed"));
        AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_paypal, "0g7", "Test 7", "Pellentesque habitant morbi tristique senectus"));
        AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_taxi, "0h8", "Test 8", "Proin iaculis, velit ac consectetur bibendum, orci nisi scelerisque"));
        AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_utensils, "0i9", "Test 9", "Ut ullamcorper nisi dui, et sagittis ante mollis vitae"));
        AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_whatsapp, "k10", "Test 10", "Donec rhoncus magna in mauris ultricies"));


// Button that opens the dialog.
        Button btnopendialog = findViewById(R.id.btnopendialog);
        btnopendialog.setOnClickListener(v -> {
AlertDialog.Builder dialogbuider = new AlertDialog.Builder(context);
    dialogbuider.setCancelable(false);
    dialogbuider.setTitle("Itens");
    ALItensValuesAdapter mAdapter = new ALItensValuesAdapter(ALitensvalues, context);
    dialogbuider.setAdapter(mAdapter, (dialog, which) -> {
        // I do not know what to do here. 
        // But I think it should be here that I start the selected items.
    });
    dialogbuider.setPositiveButton("OK", (dialogInterface, which) -> {
        // And once selected, I would like to display in textview the items that are currently selected.
    });
    dialogbuider.setNeutralButton("Clear", (dialogInterface, which) -> { 
        // Here should clear all checkboxes
    });
    AlertDialog dialog = dialogbuider.create();
    ListView listView = dialog.getListView();
    listView.setDivider(new ColorDrawable(Color.GRAY)); 
    listView.setDividerHeight(2);
    dialog.show();
        });

//Button to send to server.
        findViewById(R.id.btnsend).setOnClickListener(v -> {
             //I need to know how to retrieve the selected items.
        });
    }
Karrthik :

As mentioned by Le Thanh Tan, Interfaces are the way to go.

  1. Create MyInterface.java file and add this piece of code

    public interface MyInterface {
        void onItemChecked(int position);
    }
    
  2. Update your ALItensValues class as following

    public class ALItensValues {
      private int icon;
      private String value;
      private String titulo;
      private String descricao;
      private Boolean isChecked;
    
      public ALItensValues(int icon, String value, String titulo, String descricao, Boolean isChecked) {
       this.icon = icon;
       this.value = value;
       this.titulo = titulo;
       this.descricao = descricao;
       this.isChecked = isChecked;
      }
    
      int getIcon() { return icon; }
      String getValue() { return value; }
      String getTitulo() { return titulo; }
      String getDescricao() { return descricao; }
      Boolean getChecked() { return isChecked; }
      void setChecked(Boolean isChecked) {
        this.isChecked = isChecked;
      }
    }
    
  3. Now your Activity will be

    public class FormsMultipleSelectCustomJava extends AppCompatActivity {
    
       String selectItensServer;  
       String[] selectInitItens;
       ArrayList<ALItensValues> AlertDialogitemList = new ArrayList<>();
       ArrayList<ALItensValues> selectedItemsList = new ArrayList<>();
    
       @Override
       protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_multipleselectcustom);
    
            selectItensServer = "0b2,0e5,0f6,0h8";  
            selectInitItens = selectItensServer.split(",");
    
            AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_bicycle, "0a1", "Test 1", "Lorem ipsum dolor sit amet", true));
            AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_btc, "0b2", "Test 2", "Duis at ullamcorper quam", true));
            AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_car, "0c3", "Test 3", "Aenean aliquam sit amet nibh eget bibendum", false));
            AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_credit_card, "0d4", "Test 4", "Sed a est vel velit rutrum porta", true));
            AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_gamepad, "0e5", "Test 5", "Phasellus pellentesque arcu et fermentum tempus", false));
            AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_gift, "0f6", "Test 6", "Integer arcu leo, consequat eget tempus sed", true));
            AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_paypal, "0g7", "Test 7", "Pellentesque habitant morbi tristique senectus", false));
            AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_taxi, "0h8", "Test 8", "Proin iaculis, velit ac consectetur bibendum, orci nisi scelerisque", true));
            AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_utensils, "0i9", "Test 9", "Ut ullamcorper nisi dui, et sagittis ante mollis vitae", false));
            AlertDialogitemList.add(new ALItensValues(R.drawable.atrib_whatsapp, "k10", "Test 10", "Donec rhoncus magna in mauris ultricies", true));
    
          Button btnopendialog = findViewById(R.id.btnopendialog);
          btnopendialog.setOnClickListener(v -> {
                 AlertDialog.Builder dialogbuider = new AlertDialog.Builder(context);
                 dialogbuider.setCancelable(false);
                 dialogbuider.setTitle("Itens");
                 ALItensValuesAdapter mAdapter = new ALItensValuesAdapter(ALitensvalues, context, new MyInterface() {
                   @Override
                   public void onItemChecked(int position) 
                     {
                AlertDialogitemList.get(position).setChecked(!AlertDialogitemList.get(position).getChecked())
                     }
                  });
                dialogbuider.setAdapter(mAdapter, (dialog, which) -> {
    
                });
                dialogbuider.setPositiveButton("OK", (dialogInterface, which) -> {
    
                });
                dialogbuider.setNeutralButton("Clear", (dialogInterface, which) -> { 
                });
                AlertDialog dialog = dialogbuider.create();
                ListView listView = dialog.getListView();
                listView.setDivider(new ColorDrawable(Color.GRAY)); 
                listView.setDividerHeight(2);
                dialog.show();
           });
    
    
             findViewById(R.id.btnsend).setOnClickListener(v -> {
                 for(ALItensValues item : AlertDialogitemList) {
                      if(item.isChecked()) {
                           selectedItemsList.add(item);
                      }
                 }
                // selected items can be sent to server
          });
       }
    }
    
  4. Your Adapter

    private class ALItensValuesAdapter extends BaseAdapter {
       private ArrayList<ALItensValues> mData;
       private Context mContext;
       private MyInterface interface;
    
       ALItensValuesAdapter(ArrayList<ALItensValues> aldata, Context context, MyInterface interface) {
          this.mData = aldata;
          this.mContext = context;
          this.interface = interface;
       }
    
       @Override
       public int getCount() {
          return mData.size();
       }
    
       @Override
       public Object getItem(int position) {
          return null;
       }
    
       @Override
       public long getItemId(int position) {
           return 0;
       }
    
       @Override
       public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
               LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
               convertView = Objects.requireNonNull(mInflater).inflate(R.layout.multipleselectcustom_lines, null);
            }
    
            ImageView icon = convertView.findViewById(R.id.imgvicon);
            icon.setImageResource(mData.get(position).getIcon());
            TextView titulo = convertView.findViewById(R.id.txtv_titulo);
            titulo.setText(mData.get(position).getTitulo());
            TextView decricao = convertView.findViewById(R.id.txtv_desc);
            decricao.setText(mData.get(position).getDescricao());
            CheckBox checkbox = convertView.findViewById(R.id.chkbox);
            if(mData.get(position).getChecked()) {
                 checkbox.setChecked(true);
            } else {
                 checkbox.setChecked(false);
            }
            convertView.setOnClickListener(v -> {
                this.interface.onItemChecked(position);
                checkbox.toggle();
            });
       return convertView;
      }
    }
    

Hope this works.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=149289&siteId=1