如何在滚动时保存listview所选项目的颜色?

时间:2016-05-03 12:00:20

标签: android listview

每当我长按自定义列表视图中包含图像的项目时,图像的颜色就会改变。但滚动后,另一个listview项目的图像颜色已更改。那么我该怎样做才能保留所选项目的位置。这是我的适配器

public class SubCategories_adapter extends ArrayAdapter<Messages> {

private Context mContext;
private List<Messages> mDataSet;
SharedPreference sharedPreference;

public SubCategories_adapter(Context context, List<Messages> dataSet) {
    super(context, R.layout.listdesign_subcategories, dataSet);
    mContext = context;
    mDataSet = dataSet;
    sharedPreference = new SharedPreference();

}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = convertView;
    final ViewHolder holder;
    if (v == null) {
        v = inflater.inflate(R.layout.listdesign_subcategories, null);

        holder = new ViewHolder();
        holder.message = (TextView) v.findViewById(R.id.tv_sub);
        holder.favoriteImg = (ImageView) v.findViewById(R.id.fav_sub);
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }
    Messages msgs = (Messages) getItem(position);

    if (checkFavoriteItem(msgs)) {
        holder.favoriteImg.setImageResource(R.drawable.favourite);
        holder.favoriteImg.setTag("red");
    } else {
        holder.favoriteImg.setImageResource(R.drawable.unfavorite);
        holder.favoriteImg.setTag("grey");
    }

    holder.message.setText(mDataSet.get(position).getMessage());
    final ViewHolder finalHolder = holder;

    return v;

}

/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Messages checkProduct) {
    boolean check = false;
    List<Messages> fav = sharedPreference.getFavorites(mContext);
    if (fav != null) {
        for (Messages product : fav) {
            if (product.equals(checkProduct)) {
                check = true;
                break;
            }
        }
    }
    return check;
}

@Override
public void add(Messages product) {
    super.add(product);
    mDataSet.add(product);
    notifyDataSetChanged();
}

@Override
public void remove(Messages product) {
    super.remove(product);
    mDataSet.remove(product);
    notifyDataSetChanged();
}

static class ViewHolder {
    TextView message;
    ImageView favoriteImg;
}



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

@Override
public Messages getItem(int position) {
    return mDataSet.get(position);
}

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


@Override
public int getItemViewType(int position) {
    return position;
}

@Override
public int getViewTypeCount() {
    return getCount();
}}

/ * fragment * /

public class SubCategoryFragment extends Fragment implements
    AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

public static final String ARG_ITEM_ID = "SubCategories_list";

ListView lv_sub;
public static SubCategoryFragment instance;
Activity activity;
ArrayList<Messages> products;
SubCategories_adapter sub_adapter;
SharedPreference sharedPreference;
CustomProgressDialog progressDialog;
int responseCode;
int ID;
String MSG_NAME;
boolean islike=false;

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    progressDialog = new CustomProgressDialog(getActivity());
    activity = getActivity();
    sharedPreference = new SharedPreference();
    lv_sub = (ListView) getView().findViewById(R.id.lv_sub);
    lv_sub.setOnItemClickListener(this);
    lv_sub.setOnItemLongClickListener(this);
    products = new ArrayList<Messages>();
    try {
        new Get_message().execute();
    } catch (Exception e) {
        Log.i("Exception", e + "");
        e.printStackTrace();
    }
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    ID= Integer.parseInt(getArguments().getString("position"));
    MSG_NAME=getArguments().getString("msg_name");
    Categories_activity.toolbar_title.setText(MSG_NAME);
    instance = this;

    return inflater.inflate(R.layout.activity_sub_categories,null);
}

private class Get_message extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        JSONParser jsonParser = new JSONParser(getActivity());
        try {

             String[] json = jsonParser.sendPostReq("MY_API");

            responseCode = Integer.parseInt(json[0]);
            String str = json[1];
            Log.e("URL-->", str);
            String data = "";
            if (responseCode == 200) {
                JSONObject jsonRootObject = new JSONObject(str);
                JSONArray jsonArray = jsonRootObject.getJSONArray("result");
                for (int i = 0; i < jsonArray.length(); i++) {

                    Messages user = new Messages();
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    user.setCategories_id(jsonObject.getString("categories_id"));
                    user.setMessage_id(jsonObject.getString("message_id"));
                    user.setMessage(jsonObject.getString("messages"));
                    products.add(user);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        try {
            if (responseCode == 200) {
                int firstPosition = lv_sub.getFirstVisiblePosition();
                sub_adapter = new SubCategories_adapter(getActivity(), products);
                lv_sub.setAdapter(sub_adapter);
                lv_sub.setSelection(firstPosition);
                sub_adapter.notifyDataSetChanged();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        progressDialog.dismiss();
    }
}


@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Messages product = (Messages) parent.getItemAtPosition(position);
    Toast.makeText(activity, product.toString(), Toast.LENGTH_LONG).show();
}

@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3) {
    ImageView button = (ImageView) view.findViewById(R.id.fav_sub);

    String tag = button.getTag().toString();
    if (tag.equalsIgnoreCase("grey")) {
        sharedPreference.addFavorite(activity, products.get(position));
        Toast.makeText(activity,
                activity.getResources().getString(R.string.add_favr),
                Toast.LENGTH_SHORT).show();

        button.setTag("red");
        button.setImageResource(R.drawable.favourite);

    } else {
        sharedPreference.removeFavorite(activity, products.get(position));
        button.setTag("grey");
        button.setImageResource(R.drawable.unfavorite);
        Toast.makeText(activity,
                activity.getResources().getString(R.string.remove_favr),
                Toast.LENGTH_SHORT).show();
    }
    return true;
}

@Override
public void onResume() {
    super.onResume();
}}

0 个答案:

没有答案