1

单击按钮时,我需要从网格视图中获取复选框状态

我尝试了很多东西,但状态总是“假”

这是我的代码

这是适配器

       public class CustomSuggestFriends extends ArrayAdapter<Items_FriendsRequest> {

Context context;
dbManage objDB;
Items_FriendsRequest Items_SuggestFriends;
List<Items_FriendsRequest>items;
int Position;
SharedPreferences SharedP;
String user_id="1002", secret_id = "2143054018";
String u_id="1025", ut_ = "1";

public CustomSuggestFriends(Context context, int textViewResourceId,
        List<Items_FriendsRequest> objects) {
    super(context, textViewResourceId, objects);

    this.context = context;
}

private class viewHolder {
    private ImageView userImage;
    private TextView userName;
    private CheckBox checkbox;

}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    viewHolder holder = null;
    ImageLoader_Crop imageLoader_Crop;
    Items_SuggestFriends = getItem(position);
    Position = position;


    objDB = new dbManage(getContext());
    items = objDB.select_SuggestFriends();
    objDB.CloseDataBase();  

    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

    imageLoader_Crop = new ImageLoader_Crop(context.getApplicationContext());

    if (convertView == null) {

        convertView = inflater.inflate(R.layout.items_suggestdriends, null);
        holder = new viewHolder();

        holder.userImage = (ImageView) convertView
                .findViewById(R.id.Items_SuggestFriends_userImage);
        holder.userName = (TextView) convertView
                .findViewById(R.id.Items_SuggestFriends_NameTXT);
        holder.checkbox = (CheckBox) convertView
                .findViewById(R.id.Items_SuggestFriends_checkBox);

        holder.checkbox.setTag(position); 

        holder.checkbox.setChecked(items.get(position).isSelected());

        holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                items.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
            Log.v("Changed",items.get(getPosition).getId_()+"");
            }
        });

        convertView.setTag(holder);

    } else {
        holder = (viewHolder) convertView.getTag();
    }

    holder.userName.setText(Items_SuggestFriends.getName_());

    String SuggestF = Items_SuggestFriends.getSuggestFriendsSEND();

    if (SuggestF.equals("0")) {
        holder.checkbox.setVisibility(View.VISIBLE);
    } else if (SuggestF.equals("1")) {

        holder.checkbox.setVisibility(View.GONE);
    }

    String imageURL = "";
    imageURL = functionspackage.Constants.server_file + "1/s/"
            + Items_SuggestFriends.getId_() + "."
            + Items_SuggestFriends.getRand_() + ".jpg";

    holder.userImage.setTag(imageURL);
    imageLoader_Crop.DisplayImage(imageURL, context, holder.userImage); 

    return convertView;
}



}

这是我的课,它有一个名为发送的按钮,在这个按钮中我需要获取被检查内容的 ID

    public class SuggestFriends extends Activity {
int count;
dbManage objDB;
SharedPreferences SharedP;
String user_id, secret_id = "";
public static String u_id, ut_ = "";
Button send, cancel;

List<Items_FriendsRequest> SuggestFriendsItems;

GridView gridView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.displayphoto_from_album);
    initialise_View();

在这里我需要获取值,但它总是错误的!!!!

    send.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            count = gridView.getCount();
            objDB = new dbManage(SuggestFriends.this);
            SuggestFriendsItems = objDB.select_SuggestFriends();
            objDB.CloseDataBase();
            SparseBooleanArray sparseBooleanArray = gridView
                    .getCheckedItemPositions();

            // add the id of the ones that been checked . . to string with
            // (,)

            for (int i = 0; i < count; i++) {
                 if(sparseBooleanArray.valueAt(i) == true) {

                    Log.e(sparseBooleanArray.get(i)+"",SuggestFriendsItems.get(i).getId_()+"");
                } else if (!sparseBooleanArray.get(i)) {

                    Log.e(sparseBooleanArray.get(i) +"",SuggestFriendsItems.get(i).getId_()+"");
                    gridView.getItemAtPosition(i);

                }
            }

        }
    });

    SharedP = getSharedPreferences(functionspackage.Constants.SharedP_name,
            0);
    user_id = SharedP.getString(functionspackage.Constants.SharedP_user_id,
            null);
    secret_id = SharedP.getString(
            functionspackage.Constants.SharedP_secret_id, null);

    if (getIntent().hasExtra(functionspackage.Constants.Extra_Uid)) {
        u_id = getIntent().getStringExtra(
                functionspackage.Constants.Extra_Uid);
    }
    if (getIntent().hasExtra(functionspackage.Constants.Extra_ut)) {
        ut_ = getIntent().getStringExtra(
                functionspackage.Constants.Extra_ut);
    }

    SuggestFriends_AsyncTask Async = new SuggestFriends_AsyncTask();
    Async.execute(user_id, secret_id, u_id, ut_);

}

// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
String response = "";

class SuggestFriends_AsyncTask extends AsyncTask<String, Integer, String> {

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

        response = "";
        response = functionspackage.methodes.HTTP_fileInf_OPhotos(
                functionspackage.Constants.server_Web_Profiles
                        + "/suggest/" + params[3] + "/" + params[2],
                params[0], params[1], 0);

        functionspackage.methodes.install_JSON_SuggestFriends(
                SuggestFriends.this, response);

        objDB = new dbManage(SuggestFriends.this);
        SuggestFriendsItems = objDB.select_SuggestFriends();
        objDB.CloseDataBase();

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        CustomSuggestFriends adapterSuggestFriends = new CustomSuggestFriends(
                SuggestFriends.this, R.layout.items_suggestdriends,
                SuggestFriendsItems);
        gridView.setAdapter(adapterSuggestFriends);
        gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE);
    }

}

// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////

private void initialise_View() {

    gridView = (GridView) findViewById(R.id.DisplayPhoto_gridView);
    gridView.setNumColumns(3);
    gridView.setBackgroundColor(Color.BLACK);

    send = (Button) findViewById(R.id.SendSuggestBotton);
    cancel = (Button) findViewById(R.id.CancelsuggestFrindes);

}

}

这是日志

在此处输入图像描述

4

2 回答 2

3

使用稀疏布尔数组

在此处检查此链接

https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M

检查 Romain Guy 解决方案。使用 GridView 而不是 Listview。

类似于这里回答的那个。而不是 listview 使用 gridview。

上下滚动gridview时未选中in gridview复选框

这是另一个例子。同样使用gridview而不是Listview

如何更改列表视图中复选框的文本?

这是完整的例子

public class MainActivity extends Activity implements
AdapterView.OnItemClickListener {
    int count;
private CheckBoxAdapter mCheckBoxAdapter;

String[] GENRES = new String[] {
    "Action", "Adventure", "Animation", "Children", "Comedy",
"Documentary", "Drama",
    "Foreign", "History", "Independent", "Romance", "Sci-Fi",
"Television", "Thriller"
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final GridView listView = (GridView) findViewById(R.id.lv);

   // listView.setItemsCanFocus(false);
    listView.setTextFilterEnabled(true);
    listView.setOnItemClickListener(this);
    mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
           listView.setAdapter(mCheckBoxAdapter);
    Button b= (Button) findViewById(R.id.button1);
    b.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            StringBuilder result = new StringBuilder();
            result.append("Checked at position");
            result.append("\n");
            for(int i=0;i<mCheckBoxAdapter.mCheckStates.size();i++)
            {
                if(mCheckBoxAdapter.mCheckStates.get(i)==true)
                {

                    result.append(mCheckBoxAdapter.mCheckStates.get(i)+" at"+i);
                    result.append("\n");

                }

            }
            Toast.makeText(MainActivity.this, result, 10000).show();
        }

    });




   }

public void onItemClick(AdapterView parent, View view, int
position, long id) {
    mCheckBoxAdapter.toggle(position);
}

class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{  private SparseBooleanArray mCheckStates;
   LayoutInflater mInflater;
    TextView tv1,tv;
    CheckBox cb;
    String[] gen;
    CheckBoxAdapter(MainActivity context, String[] genres)
    {
        super(context,0,genres);
        mCheckStates = new SparseBooleanArray(genres.length);
        mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        gen= genres;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return gen.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub

        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View vi=convertView;
        if(convertView==null)
         vi = mInflater.inflate(R.layout.checkbox, null); 
         tv= (TextView) vi.findViewById(R.id.textView1);

         cb = (CheckBox) vi.findViewById(R.id.checkBox1);
         tv.setText("Name :"+ gen [position]);
         cb.setTag(position);
         cb.setChecked(mCheckStates.get(position, false));
        cb.setOnCheckedChangeListener(this);
        return vi;
    }
     public boolean isChecked(int position) {
            return mCheckStates.get(position, false);
        }

        public void setChecked(int position, boolean isChecked) {
            mCheckStates.put(position, isChecked);

        }

        public void toggle(int position) {
            setChecked(position, !isChecked(position));

        }
    @Override
    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
         mCheckStates.put((Integer) buttonView.getTag(), isChecked);    

    }

}

}

活动主.xml

<RelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent">

     <GridView
     android:id="@+id/lv"
     android:layout_width="wrap_content"
      android:numColumns="2"
      android:layout_height="wrap_content"
      android:layout_above="@+id/button1"/>
      <Button
          android:id="@+id/button1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentBottom="true"
          android:layout_centerHorizontal="true"
          android:text="Button" />

    </RelativeLayout>

复选框.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="34dp"
        android:text="TextView" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginRight="22dp"
        android:layout_marginTop="23dp" />

</RelativeLayout>

快照

在此处输入图像描述

于 2013-09-29T11:34:27.477 回答
0

在我看来,你的问题中有很多不必要的代码(不过总比太少好),请尝试更改:

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
            // -- buttonView.isChecked() changed to isChecked -- //
            items.get(getPosition).setSelected(isChecked); // Set the value of checkbox to maintain its state.
        Log.v("Changed",items.get(getPosition).getId_()+"");
        }

如果这不起作用,请清楚地表明您在哪里读取了错误值并期望为真。

于 2013-09-29T11:21:51.807 回答