有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android:从主活动按钮确定在listview中选中哪个复选框

我已将以下代码用于带有自定义适配器的ListView。代码对我来说很有效

在ListView中,每个ListView行中都有一个复选框、TextView、ImageView和按钮。数据将通过HttpPost方法获取,并在listview的每一行中分配,没有问题

我想获得在listview中选中的所有复选框,单击主活动的按钮

我读了很多文章和例子,但都没有得到正确的答案

代码为:main活动。java记录单击哪个按钮,并以“单击按钮”的形式给出祝酒词

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 安卓.app.Activity;
import 安卓.app.ProgressDialog;
import 安卓.content.Intent;
import 安卓.os.AsyncTask;
import 安卓.os.Bundle;
import 安卓.util.Log;
import 安卓.view.View;
import 安卓.view.View.OnClickListener;
import 安卓.widget.Button;
import 安卓.widget.CheckBox;
import 安卓.widget.LinearLayout;
import 安卓.widget.ListView;
import 安卓.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);
}
}

代码为:ListAdapter。java文件

package com.example.listviewimageloadingexample;

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

import 安卓.content.Context;
import 安卓.content.Intent;
import 安卓.util.Log;
import 安卓.view.LayoutInflater;
import 安卓.view.View;
import 安卓.view.View.OnClickListener;
import 安卓.view.ViewGroup;
import 安卓.widget.BaseAdapter;
import 安卓.widget.Button;
import 安卓.widget.CheckBox;
import 安卓.widget.CompoundButton;
import 安卓.widget.ImageView;
import 安卓.widget.TextView;
import 安卓.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;
    }
}

代码:listitem。xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:orientation="vertical" >

    <LinearLayout
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content" >

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

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

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

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

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

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

    </LinearLayout>

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

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

    </LinearLayout>

</LinearLayout>

代码:listview\u main。xml

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

    <LinearLayout
        安卓:layout_width="match_parent"
        安卓:layout_height="match_parent"
        安卓:orientation="vertical" >

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

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

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

        </LinearLayout>

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

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

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

    </LinearLayout>

</ScrollView>

共 (3) 个答案

  1. # 3 楼答案

    谢谢大家

    我从以下代码中找到了答案Link.从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();
            }
        }
    }