如何使用复选框setMultiChoiceItems创建自定义对话框,接收和发送数据?

时间:2019-05-16 02:47:12

标签: java android

我需要使用类似setMultiChoiceItems样式的对话框,但需要更多信息,所以我使用的是自定义布局。

我的布局包含一个图像字段,另一个标题字段,另一个描述字段以及一个复选框中的另一个字段。

enter image description here

我已经设法使其工作了:

enter image description here

我知道我需要使用setAdapter而不是setMultiChoiceItems。到目前为止一切顺利。

我的问题是如何打开已经选择了某些选项的对话框?然后接收所有选择的项目发送到服务器?

使用setMultiChoiceItems可以使它像这样工作:

enter image description here

但是我似乎无法使用自定义布局。

这是我的代码:

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

#####适配器-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;
    }
}

####布局索引-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>

####活动类别####

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

2 个答案:

答案 0 :(得分:1)

正如Le Thanh Tan所说,接口是必经之路。

  1. 创建MyInterface.java文件并添加这段代码

    public interface MyInterface {
        void onItemChecked(int position);
    }
    
  2. 如下更新您的ALItensValues类

    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. 现在您的活动将是

    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. 您的适配器

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

希望这行得通。

答案 1 :(得分:0)

我想你可以做到的。

添加一个HashSet来将选中的项目保存在Adapter类中,并添加一些方法来获取/设置选中的项目,例如:

private class ALItensValuesAdapter extends BaseAdapter {

    ... other code

    // save checked items
    private HashSet<ALItensValues> mCheckedSet = new HashSet<ALItensValues>();

    public HashSet<ALItensValues> getCheckedSet(){
        return mCheckedSet;
    }

    public void setCheckedSet(HashSet<ALItensValues> set){
        this.mCheckedSet = set;
        notifyDatasetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ... other code

        // delete code
        // convertView.setOnClickListener(v -> {
        //    checkbox.toggle();
        // });
        // add code
        final ALItensValues item = mData.get(position);
        // set check state by mCheckedSet
        checkbox.setCheck(mCheckedSet.contains(item));
        convertView.setOnClickListener(v -> {
            if (mCheckSet.contains(item)){
                mCheckSet.remove(item);
            } else {
                mCheckSet.add(item);
            }
            notifyDatasetChanged();
        });
        return convertView;
    }
}

然后您可以使用setCheckedSet / getCheckedSet来设置或获取选中的项目。

在您的活动课中

dialogbuider.setPositiveButton("OK", (dialogInterface, which) -> {
    // get the check items when click 'OK' button
    HashSet<ALItensValues> checkedSet = mAdapter.getCheckedSet();
});