简体   繁体   English

Android:通过“主要活动”按钮确定在列表视图中选中了哪个复选框

[英]Android : Determine which checkbox is checked in listview from the Main activity button

I have use the following code for ListView with custom adapter. 我将以下代码用于带有自定义适配器的ListView。 The Code is Working fine for me, 该代码对我来说很好

In ListView there is one checkbox, TextView, ImageView and Button in every ListView Row. 在ListView中,每个ListView行中都有一个复选框,即TextView,ImageView和Button。 Data will fetched Through HttpPost method and assign in every row of listview there is no problem. 数据将通过HttpPost方法获取并分配到listview的每一行中,没有问题。

I want to get the all the checkbox which is checked in listview, Click on Button of Main Activity. 我想获取所有在列表视图中选中的复选框,单击“主要活动”按钮。

I have read many article and example but could not get the proper answer these. 我已经阅读了许多文章和示例,但无法获得正确的答案。

Code for : MainActivity.java file which button is clicked and give the Toast as "button is clicked". 用于: MainActivity.java文件的代码,单击哪个按钮,并将Toast命名为“单击按钮”。

package com.example.listviewimageloadingexample;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;

    static String RANK = "rank";
    static String COUNTRY = "country";
    static String POPULATION = "population";
    static String FLAG = "flag";
    Button processedAllBtn;
    CheckBox processAll;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);

        processedAllBtn=(Button) findViewById(R.id.btnProcessedAllAbove);
        processedAllBtn.setOnClickListener(this);

        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listview);

        Object obj=(ListViewAdapter)getLastNonConfigurationInstance();
        if(obj==null)
        {
            // Execute DownloadJSON AsyncTask
            new DownloadJSON().execute();
        }
        else
        {
            adapter=(ListViewAdapter)obj;
            setListView();
        }
    }

    @Override
    public void onClick(View arg0) {
        switch(arg0.getId())
        {
            case R.id.btnProcessedAllAbove:
            //Toast.makeText(getApplicationContext(), "button is clicked "+arg0.getId(), Toast.LENGTH_SHORT).show();

            break;
        }
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {

        super.onPreExecute();

        // Create a progressdialog
        mProgressDialog = new ProgressDialog(MainActivity.this);

        // Set progressdialog title
        mProgressDialog.setTitle("Android JSON Parse Tutorial");

        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);

        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {

        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();

        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONfunctions.getJSONfromURL("WEBSERVICE_URL");

        try {
            // Locate the array name in JSON
            //jsonarray = jsonobject.getJSONArray("worldpopulation");
            jsonarray = jsonobject.getJSONArray("students");
            String flag="";

            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject jsonobject = jsonarray.getJSONObject(i);

                JSONObject student_object = jsonobject.getJSONObject("students");

                // Retrive JSON Objects
                map.put("rank", student_object.getString("id"));
                map.put("country", student_object.getString("name"));
                map.put("population", student_object.getString("roll_number"));

                flag = student_object.getString("student_photo");
                flag = flag.replace(" ", "%20");

                map.put("flag", "WEBSERVICE_URL"+flag);
                // Set the JSON Objects into the array
                arraylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {

        setListView();

        // Close the progressdialog
        mProgressDialog.dismiss();
    }
}

@Override
public Object onRetainNonConfigurationInstance() {
    return adapter;
}

public void setListView()
{
    if(adapter==null)
    {
        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(MainActivity.this, arraylist);
    }

    // Set the adapter to the ListView
    listview.setAdapter(adapter);
}
}

Code for : ListAdapter .java File 代码: ListAdapter .java文件

package com.example.listviewimageloadingexample;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();
    boolean[] itemChecked;

    public ListViewAdapter(Context context, ArrayList<HashMap<String, String>> arraylist)
    {
        super();
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
        itemChecked = new boolean[data.size()];
    }

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

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

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

    public class ViewHolder
    {
        TextView rank;
        TextView country;
        TextView population;
        Button processedBtn;
        ImageView flag;
        CheckBox processedCheckBox;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {
        View view=convertView;
        final ViewHolder viewHolder;
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if(view == null)
        {

            view = inflater.inflate(R.layout.listview_item, null);

            viewHolder= new ViewHolder();

            // Locate the TextViews in listview_item.xml
            viewHolder.rank = (TextView) view.findViewById(R.id.rank);
            viewHolder.country = (TextView) view.findViewById(R.id.country);
            viewHolder.population = (TextView) view.findViewById(R.id.population);

            // Locate the ImageView in listview_item.xml
            viewHolder.flag = (ImageView) view.findViewById(R.id.flag);

            viewHolder.processedBtn = (Button) view.findViewById(R.id.btnProcessed);
            viewHolder.processedCheckBox = (CheckBox)view.findViewById(R.id.processedCheckBox);

            view.setTag(viewHolder);
        }
        else
        {
            viewHolder=(ViewHolder)view.getTag();
        }

        // Get the position
        resultp = data.get(position);

        // Capture position and set results to the TextViews
        viewHolder.rank.setText(resultp.get(MainActivity.RANK));
        viewHolder.country.setText(resultp.get(MainActivity.COUNTRY));
        viewHolder.population.setText(resultp.get(MainActivity.POPULATION));

        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), viewHolder.flag);

        viewHolder.processedBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {

            // Get the position
            resultp = data.get(position);

            Intent intent = new Intent(context, SingleItemView.class);

            // Pass all data rank
            intent.putExtra("rank", resultp.get(MainActivity.RANK));

            // Pass all data country
            intent.putExtra("country", resultp.get(MainActivity.COUNTRY));

            // Pass all data population
            intent.putExtra("population",resultp.get(MainActivity.POPULATION));

            // Pass all data flag
            intent.putExtra("flag", resultp.get(MainActivity.FLAG));

            // Start SingleItemView Class
            context.startActivity(intent);
        }
    });

    viewHolder.processedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub

            itemChecked[position]=(!itemChecked[position]);
            viewHolder.processedCheckBox.setChecked(itemChecked[position]);
        }
        });
        return view;
    }
}

Code for : listitem.xml 代码: listitem.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" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <CheckBox
            android:id="@+id/processedCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:saveEnabled="false" />

        <ImageView
            android:id="@+id/flag"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center_vertical|center_horizontal"
            android:padding="5dp"/>

        <TextView
            android:id="@+id/rank"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:text="id"
            android:textStyle="bold"
            android:visibility="gone" />

        <TextView
            android:id="@+id/country"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:text="Name"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/population"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:text="Roll_No"
            android:textStyle="bold"
            android:visibility="gone" />

        <Button
            android:id="@+id/btnProcessed"
            android:layout_width="90dp"
            android:layout_height="30dp"
            android:textSize="15sp"
            android:layout_gravity="center_vertical|center_horizontal"
            android:background="@drawable/buttonshape"
            android:text="Processed"
            android:textColor="#FFFFFF"
            android:layout_marginLeft="2dp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <View
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:background="#000000" />

    </LinearLayout>

</LinearLayout>

Code for : listview_main.xml 的代码:listview_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <CheckBox
                android:id="@+id/checkAllAbove"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Select All" />

            <Button
                android:id="@+id/btnProcessedAllAbove"
                android:layout_width="90dp"
                android:layout_height="30dp"
                android:layout_marginLeft="119dp"
                android:background="@drawable/buttonshape"
                android:text="Processed"
                android:textColor="#FFFFFF"
                android:textSize="15sp" />

        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#000000" />

        <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_height="320dp" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#000000" />

    </LinearLayout>

</ScrollView>

there is a checkbox getTag() method, use this with some logic and you should be fine 有一个复选框getTag()方法,结合一些逻辑使用它,您应该会很好

see: http://amitandroid.blogspot.in/2013/03/android-listview-with-checkbox-and.html 参见: http : //amitandroid.blogspot.in/2013/03/android-listview-with-checkbox-and.html

Take a look on this very good tutorial: 看一下这个非常好的教程:

http://www.vogella.com/tutorials/AndroidListView/article.html#listviewselection http://www.vogella.com/tutorials/AndroidListView/article.html#listviewselection

It used the setTag() / getTag() functions. 它使用了setTag()/ getTag()函数。

Thanks to everyone. 谢谢大家。

I Found answer from these Link. 我从这些链接中找到了答案 Following code get all the objects from listview. 以下代码从listview获取所有对象。

...
@Override
public void onClick(View arg0)
{
    CheckBox cb;
    for (int x = 0; x <listview.getChildCount();x++)
    {
        TextView tvRank=(TextView)listview.getChildAt(x).findViewById(R.id.rank);
        TextView tvCountry=(TextView)listview.getChildAt(x).findViewById(R.id.country);
        TextView tvPopulation=(TextView)listview.getChildAt(x).findViewById(R.id.population);

        String rank=tvId.getText().toString();
        String country=tvName.getText().toString();
        String population=tvRno.getText().toString();

        cb = (CheckBox)listview.getChildAt(x).findViewById(R.id.processedCheckBox);
        if(cb.isChecked())
        {
            Toast.makeText(getApplicationContext(),rank+"-"+country+"-"+population, Toast.LENGTH_SHORT).show();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android复选框选中一个活动,然后按钮出现在另一个活动中 - Android checkbox checked in one activity and then button appears in another activity 如何从listView中按下的按钮访问主活动中的数据? - How to access data in main Activity from a button pressed in listView? 按下按钮后计算已选中复选框的百分比,并在另一个活动中显示百分比(android) - Calculate percentage of checked checkbox after press a button and show percentage in another activity (android) 将数据从 Main 活动保存到 ListView 活动 - Save data from Main activity to a ListView activity 如何从Android中的片段访问主要活动按钮 - how to access main activity button from fragment in android 如何在android的主要活动中声明另一个活动的按钮? - How to declare a button from another activity in the main one in android? 确定Android相机活动所使用的相机 - Determine which camera used by Android camera activity 在列表视图中处理选中然后未选中的复选框的值 - Handle checked and then unchecked checkbox's value in listview android Android-如何在更改活动后保存复选框状态(已选中/未选中) - Android - How to save checkbox state (checked/unchecked) after changing activity 带有Checkbox,Textview和按钮的Listview在android中无法正常工作? - Listview with Checkbox,Textview and button not working correctly in android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM