我已经使用自定义采用者类和多个复选框选择实现了ListView
。它的工作正常。之后,我在 ListView 中搜索了名称。如果我检查了行项目,那么我在搜索中搜索名称,搜索位置已更改。请帮我解决这个问题。
模型类
public class FullUser {
String name=null;
String id=null;
boolean checked;
public FullUser(String name, String id,boolean checked){
this.name=name;
this.id = id;
this.checked = checked;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getId(){
return this.id;
}
public void setId(String id){
this.id = id;
}
public Boolean getChecked(){
return this.checked;
}
public void setChecked(Boolean checked){
this.checked = checked;
}
@Override
public String toString() {
return this.name;
}
}
适配器类
public class FullUserAdapter extends ArrayAdapter<FullUser> {
private ArrayList<FullUser> originalList;
private ArrayList<FullUser> fullUsers;
private SubjectFilter filter;
public FullUserAdapter(Context context, int resource, ArrayList<FullUser> fullUsers) {
super(context, resource, fullUsers);
this.fullUsers = new ArrayList<FullUser>();
this.fullUsers.addAll(fullUsers);
this.originalList = new ArrayList<FullUser>();
this.originalList.addAll(fullUsers);
}
@Override
public int getCount() {
return fullUsers.size();
}
@Override
public FullUser getItem(int position) {
return fullUsers.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public Filter getFilter() {
if (filter == null){
filter = new SubjectFilter();
}
return filter;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("UserConvertView", String.valueOf(position));
View row;
if (convertView == null) {
row = LayoutInflater.from(getContext()).inflate(R.layout.list_row_with_checkbox, parent, false);
}else{
row = convertView;
}
holder = new ViewHolder();
holder.name_view = (TextView) row.findViewById(R.id.nameText);
holder.firstchar_view = (TextView) row.findViewById(R.id.first_char);
holder.groupid = (TextView) row.findViewById(R.id.rowid);
holder.checkBox =(CheckBox) row.findViewById(R.id.cbBox);
final FullUser group =getItem(position);
holder.groupid.setText(group.getId());
//holder.checkBox.setChecked(checkedHolder[position]);
String communityname_text = group.getName();
holder.name_view.setText(group.getName());
String firstchar = communityname_text.substring(0, 1);
holder.firstchar_view.setText(firstchar);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true)
group.setChecked(true);
else
group.setChecked(false);
}
});
row.setTag(holder);
return row;
}
private class SubjectFilter extends Filter
{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
constraint = constraint.toString().toLowerCase();
ArrayList<FullUser> filteredItems = new ArrayList<FullUser>();
for(int i = 0, l = fullUsers.size(); i < l; i++)
{
FullUser group = fullUsers.get(i);
if(group.toString().toLowerCase().contains(constraint)) {
FullUser grouplistss = new FullUser(group.getName(),group.id,group.getChecked());
filteredItems.add(grouplistss);
}
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,Filter.FilterResults results) {
if(results.count > 0) {
fullUsers = (ArrayList<FullUser>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = fullUsers.size(); i < l; i++)
add(fullUsers.get(i));
} else {
notifyDataSetInvalidated();
}
}
}
private class ViewHolder {
TextView name_view;
TextView firstchar_view;
TextView groupid;
CheckBox checkBox;
}
}
提前致谢。
答案 0 :(得分:1)
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
group.setChecked(true);
int pos = originalList.indexOf(group)
originalList.get(pos).setChecked(true);
fullUsers.get(position).setChecked(true);
}else{
group.setChecked(false);
int pos = originalList.indexOf(group)
originalList.get(pos).setChecked(true);
fullUsers.get(position).setChecked(false);
}
}
答案 1 :(得分:0)
使用SparseBooleanArray
public class FullUserAdapter extends ArrayAdapter<FullUser> {
private ArrayList<FullUser> originalList;
private ArrayList<FullUser> fullUsers;
private SubjectFilter filter;
SparseBooleanArray booleanArray ;
public FullUserAdapter(Context context, int resource, ArrayList<FullUser> fullUsers) {
super(context, resource, fullUsers);
this.fullUsers = new ArrayList<FullUser>();
this.fullUsers.addAll(fullUsers);
this.originalList = new ArrayList<FullUser>();
this.originalList.addAll(fullUsers);
booleanArray = new SparseBooleanArray();
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
.
.
.
final FullUser group =getItem(position);
holder.groupid.setText(group.getId());
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked(booleanArray.get(group.getId().hashCode(),false));
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
booleanArray.put(group.getId().hashCode(), isChecked);
}
});
.
.
.
return row;
}
public ArrayList<FullUser> getSelectedItems() {
ArrayList<FullUser> list = new ArrayList<>();
for(FullUser group:fullUsers){
if(booleanArray.get(group.getId().hashCode(), false)){
list.add(group);
}
}
return list;
};
}
答案 2 :(得分:0)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".dashboard.VoterListActivity">
<ProgressBar
android:id="@+id/reqprogressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
<ListView
android:id="@+id/voter_lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btn_show_me"
android:divider="@null"/>
<Button
android:id="@+id/btn_show_me"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:background="@drawable/n_btn"
android:text="@string/add_family_numbers"
android:visibility="gone"
android:textColor="#ffffff"
android:textSize="20sp" />
</RelativeLayout>
Java代码
public Class Actvity extends AppCompatActivity {
ProgressBar progressBar;
ListView listView;
VoterDao voterDao;
String Token, Userid, Appid, Deviceid;
MenuItem searchview;
VoterListAdapter adapter;
String pid;
VoterDatum friend;
String value;
CheckBox mCheckBox;
Button btn_show_me;
ArrayList<VoterDatum> friends;
ListView1Adapter adapter1;
VoterDatum Model;
StringBuilder stringBuilder;
String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voter_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.voter_list);
stringBuilder = new StringBuilder();
Token = Util.getStringFromSP(this, "token");
Userid = Util.getStringFromSP(this, "user_id");
Appid = Util.getStringFromSP(this, "app_id");
Deviceid = Util.getStringFromSP(this, "device_id");
initViews();
getVoterData();
btn_show_me.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int i = 0;
if (friends.size() == i) { //do nothing
}
while (friends.size() > i) {
int count = friends.size();
Model = friends.get(i);
if (Model.isChecked()) {
Log.i("ListActivity", "here" + friends.get(i).getCitizenId());
stringBuilder.append("," + friends.get(i).getCitizenId());
name = stringBuilder.toString();
String joinedString = Model.getCitizenId().toString();
Log.d("ls", "" + name);
name = name.substring(1);
Log.d("fs", name);
sendToServer();
}
i++; // rise i
}
}
});
}
private void sendToServer() {
Intent intent = new Intent(VoterListActivity.this, AddFamilyNuberByVoterList.class);
intent.putParcelableArrayListExtra("CheckedList", friends);
startActivity(intent);
finish();
}
private void getVoterData() {
if (Util.isNetworkAvailable(this)) {
progressBar.setVisibility(View.VISIBLE);
SendRequestToServer();
} else {
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_connection, Snackbar.LENGTH_SHORT).show();
return;
}
}
private void SendRequestToServer() {
try {
RegistrationApi api = ServiceGenerator.createService(RegistrationApi.class);
retrofit2.Call<VoterDao> call = api.togetVoters(Userid, Token, Appid, Deviceid);
call.enqueue(new Callback<VoterDao>() {
@Override
public void onResponse(Call<VoterDao> call, Response<VoterDao> response) {
if (response.isSuccessful()) {
voterDao = response.body();
if (voterDao.getAddData().getStatus().equals(1)) {
searchview.setVisible(true);
progressBar.setVisibility(View.GONE);
friends = (ArrayList<VoterDatum>) voterDao.getAddData().getData();
adapter1 = new ListView1Adapter(getApplicationContext(), R.layout.list_voter, friends);
listView.setAdapter(adapter1);
btn_show_me.setVisibility(View.VISIBLE);
} else {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_data_found, Snackbar.LENGTH_SHORT).show();
}
} else {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_data_found + response.message(), Snackbar.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<VoterDao> call, Throwable t) {
try {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, "" + t.getMessage(), Snackbar.LENGTH_SHORT).show();
Log.d("message", "" + t.getMessage());
System.out.println("onFAilureExecute" + t.getMessage());
if (t != null)
t.printStackTrace();
} catch (Throwable th) {
th.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void initViews() {
progressBar = findViewById(R.id.reqprogressbar);
listView = findViewById(R.id.voter_lv);
btn_show_me = findViewById(R.id.btn_show_me);
}
@Override
public boolean onSupportNavigateUp() {
startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
return true;
}
@Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
searchview = menu.findItem(R.id.action_search);
final SearchView searchViewAndroidActionBar = (SearchView) MenuItemCompat.getActionView(searchview);
searchViewAndroidActionBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter1.getFilter().filter(newText);
return false;
}
});
View closeButton = searchViewAndroidActionBar.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//handle click
searchViewAndroidActionBar.setIconified(true);
}
});
return super.onCreateOptionsMenu(menu);
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocalHelper.onAttach(base));
}
private class ListView1Adapter extends BaseAdapter {
ListView1Adapter.ViewHolder holder;
private Context activity;
private ArrayList<VoterDatum> Friends;
private ArrayList<VoterDatum> mList;
private final String TAG = ListViewAdapter.class.getSimpleName();
boolean[] checkedItems;
public ListView1Adapter(Context applicationContext, int list_voter, ArrayList<VoterDatum> list) {
this.activity = applicationContext;
this.Friends = list;
this.mList = list;
Log.i(TAG, "init adapter");
checkedItems = new boolean[mList.size()];
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
holder = null;
final int pos = position;
// inflate layout from xml
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.list_voter, parent, false);
// get all UI view
holder = new ListView1Adapter.ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ListView1Adapter.ViewHolder) convertView.getTag();
}
friend = mList.get(position);
String nameS = friend.getFirstname() + " " + friend.getLastname();
String namesS = friend.getVoterId();
String lname = friend.getLfname() + " " + friend.getLlastname();
//set Friend data to views
String Photo = friend.getPhoto();
if (Photo.isEmpty() || Photo == null) {
holder.image.setImageResource(R.mipmap.ic_launcher);
} else {
Picasso.with(activity).load(Photo).transform(new CircleTransform()).into(holder.image);
}
holder.name.setText(nameS);
holder.lanname.setText(lname);
holder.voterid_tv.setText(namesS);
holder.check.setChecked(friend.isChecked());
holder.check.setTag(friend);
holder.check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
VoterDatum itemobj = (VoterDatum) cb.getTag();
if (mList.get(Integer.valueOf(pos)).isChecked()) {
cb.setSelected(false);
mList.get(Integer.valueOf(pos)).setIsChecked(false);
notifyDataSetChanged();
} else {
cb.setSelected(true);
mList.get(Integer.valueOf(pos)).setIsChecked(true);
notifyDataSetChanged();
}
}
});
return convertView;
}
private class ViewHolder {
private ImageView image;
private TextView name, lanname, voterid_tv;
private CheckBox check;
public ViewHolder(View v) {
image = v.findViewById(R.id.profile_iv);
name = (TextView) v.findViewById(R.id.name_tv);
lanname = (TextView) v.findViewById(R.id.desig_tv);
voterid_tv = (TextView) v.findViewById(R.id.voterid_tv);
check = (CheckBox) v.findViewById(R.id.chkEnable);
}
}
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<VoterDatum> filteredResults = null;
if (constraint.length() == 0) {
filteredResults = Friends;
} else {
filteredResults = (ArrayList<VoterDatum>) getFilteredResults(constraint.toString().toLowerCase());
}
results.values = filteredResults;
return results;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults results) {
mList = (ArrayList<VoterDatum>) results.values;
notifyDataSetChanged();
}
};
}
protected List<VoterDatum> getFilteredResults(String s) {
ArrayList<VoterDatum> results = new ArrayList<>();
for (VoterDatum item : Friends) {
String TotalSearch = item.getFirstname() + " " + item.getLastname();
if (TotalSearch.toLowerCase().contains(s) || item.getVoterId().toLowerCase().contains(s)) {
results.add(item);
}
}
return results;
}
public ArrayList<VoterDatum> getAllData() {
return mList;
}
}
}
模型类
public class VoterDatum implements Parcelable {
@SerializedName("citizen_id")
@Expose
private String citizenId;
private boolean isChecked;
public static final Parcelable.Creator<VoterDatum> CREATOR = new Parcelable.Creator<VoterDatum>() {
public VoterDatum createFromParcel(Parcel in) {
return new VoterDatum(in);
}
public VoterDatum[] newArray(int size) {
return new VoterDatum[size];
}
};
public VoterDatum(Parcel in) {
this.citizenId = in.readString();
this.isChecked = in.readByte() != 0;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.citizenId);
dest.writeByte((byte) (this.isChecked ? 1 : 0));
}
public VoterDatum(String citizenId, boolean gender) {
this.citizenId = citizenId;
this.isChecked = false; // not selected when create
}
@SerializedName("status")
@Expose
private String status;
@SerializedName("firstname")
@Expose
private String firstname;
@SerializedName("lastname")
public boolean isChecked() {
return isChecked;
}
public void setIsChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCitizenId() {
return citizenId;
}
public void setCitizenId(String citizenId) {
this.citizenId = citizenId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getLfname() {
return lfname;
}
public void setLfname(String lfname) {
this.lfname = lfname;
}
}
从其他类获取数据
public class ACtivity extends AppCompatActivity implements View.OnClickListener {
String Mvoterid;
GPSTracker gps;
String Token, Userid, Deviceid, Appid, Language;
Button submit_btn;
ProgressBar progressBar;
AddFamilynumberbyvoterDao addFamilynumberbyvoterDao;
// ArrayList<VoterDatum> checkedList;
List<VoterDatum> checkedList;
LinearLayout container;
VoterDatum Model;
ListView list_item;
String join;
int position;
String userName;
String name;
StringBuilder stringBuilder;
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_family_nuber_by_voter_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.add_family_numbers);
VoterID = getIntent().getStringExtra("voterIDs");
stringBuilder= new StringBuilder();
checkedList = new ArrayList<VoterDatum>(); // initializing list
container = (LinearLayout) findViewById(R.id.layout);
getLocation();
initViews();
initListeners();
getDataFromIntent();
generateDataToContainerLayout();
}
@RequiresApi(api = Build.VERSION_CODES.O)
@SuppressLint("InflateParams")
private void generateDataToContainerLayout() {
int i = 0;
if (checkedList.size() == i) { //do nothing
}
while (checkedList.size() > i) {
int count = checkedList.size();
Model = checkedList.get(i);
if (Model.isChecked()) {
Log.i("ListActivity", "here" + checkedList.get(i).getCitizenId());
stringBuilder.append(","+checkedList.get(i).getCitizenId());
name=stringBuilder.toString();
String joinedString = Model.getCitizenId().toString();
Log.d("ls", "" + name);
name=name.substring(1);
Log.d("fs",name);
}
i++; // rise i
}
}
private void getDataFromIntent() {
checkedList = getIntent().getParcelableArrayListExtra("CheckedList");
}