如何在ListView中显示过滤结果时如何获取正确的项目,以及在选择过滤结果时如何在另一个片段中显示正确的输出,到目前为止,这是我当前的代码。
到目前为止我的代码:
YourGroup.java
package com.findforme.www.myapplication;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class YourGroup extends Fragment implements SearchView.OnQueryTextListener,SearchView.OnCloseListener{
private String TAG = YourGroup.class.getSimpleName();
private ListView gridView;
private SearchView mSearchView;
ListAdapterShowGroups adapter;
ArrayList<your_groups> your_groupList;
public static YourGroup newInstance() {
YourGroup fragment = new YourGroup();
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void findViews(View view) {
your_groupList = new ArrayList<>();
mSearchView = view.findViewById(R.id.floating_search_view);
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnCloseListener(this);
gridView = view.findViewById(R.id.lv_showGroup);
gridView.setTextFilterEnabled(false);
new GetGroups().execute();
}
@Override
public boolean onClose() {
final FilterHelper filterHelper = new FilterHelper(your_groupList,adapter,getActivity());
adapter = new ListAdapterShowGroups(filterHelper.currentList,getActivity());
gridView.setAdapter(adapter);
return false;
}
@Override
public boolean onQueryTextSubmit(String s) {
adapter.getFilter().filter(s);
return false;
}
@Override
public boolean onQueryTextChange(String query) {
adapter.getFilter().filter(query);
return false;
}
public static class FilterHelper extends Filter{
ArrayList<your_groups> currentList;
ListAdapterShowGroups adapter;
Context c;
FilterHelper(ArrayList<your_groups> currentList, ListAdapterShowGroups adapter, Context c){
this.currentList = currentList;
this.adapter = adapter;
this.c = c;
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if(constraint != null && constraint.length()>0){
constraint = constraint.toString().toLowerCase();
ArrayList<your_groups> foundFilters = new ArrayList<>();
your_groups your_group = null;
for (int i=0;i<currentList.size();i++){
your_group = currentList.get(i);
if(your_group.GroupName.toLowerCase().contains(constraint)){
foundFilters.add(your_group);
}
}
filterResults.count=foundFilters.size();
filterResults.values=foundFilters;
} else {
filterResults.count =currentList.size();
filterResults.values=currentList;
}
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
if(filterResults.count == 0){
adapter.invalidate();
} else {
adapter.setYourGroups((ArrayList<your_groups>)filterResults.values);
adapter.refresh();
}
}
}
private class GetGroups extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//Toast.makeText(getActivity(), "Retrieving data", Toast.LENGTH_SHORT).show();
}
@Override
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
int id = MainActivity.user.getId();
String user_id = Integer.toString(id);
//String url = "https://findforme2018.000webhostapp.com/show_groups_joined.php?id="+user_id;
String url = "http://192.168.211.1/Capstone%202018/FindForMe/show_groups_joined.php?id="+user_id;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if( jsonStr != null){
try{
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray groups = jsonObj.getJSONArray("group_join");
your_groups your_groups;
your_groupList = new ArrayList<>();
for (int i = 0; i < groups.length(); i++){
JSONObject c = groups.getJSONObject(i);
your_groups = new your_groups();
your_groups.setGroupName(c.getString("group_name"));
your_groups.setId(c.getInt("group_id"));
your_groupList.add(your_groups);
}
}catch (final JSONException e){
Log.e(TAG, "Error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(),
"No groups join yet",
Toast.LENGTH_LONG).show();
}
});
}
}
else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter = new ListAdapterShowGroups(your_groupList,getActivity());
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int id = your_groupList.get(i).id;
String group_id = Integer.toString(id);
String groupname = your_groupList.get(i).GroupName;
Bundle args = new Bundle();
args.putString("group_id", group_id);
args.putString("groupname", groupname);
SelectedGroup fragment = new SelectedGroup();
fragment.setArguments(args);
Toast.makeText(getActivity(),
groupname,
Toast.LENGTH_LONG).show();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_main
, fragment).addToBackStack(null).commit();
}
});
}
}
View myView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_your_group, container, false);
findViews(myView);
return myView;
}
}
这是在列表视图及其过滤器中显示数据的适配器
package com.findforme.www.myapplication;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class ListAdapterShowGroups extends BaseAdapter implements Filterable{
Context context;
private ArrayList<your_groups> valueList;
private YourGroup.FilterHelper filterHelper;
ListAdapterShowGroups(ArrayList<your_groups> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
}
@Override
public int getCount()
{
return this.valueList.size();
}
@Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
@Override
public long getItemId(int position)
{
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ListAdapterShowGroups.ViewItem viewItem;
if(convertView == null)
{
viewItem = new ListAdapterShowGroups.ViewItem();
LayoutInflater layoutInflater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.customgroup_layout,null);
viewItem.image = convertView.findViewById(R.id.groupImage);
viewItem.groupname = convertView.findViewById(R.id.tv_groupName);
convertView.setTag(viewItem);
}
else
{
viewItem = (ListAdapterShowGroups.ViewItem)convertView.getTag();
}
viewItem.groupname.setText(valueList.get(position).getGroupName());
String img = valueList.get(position).getGroupName();
//Glide.with(this.context).load("https://findforme2018.000webhostapp.com/Group_Image/"+img+".jpg").asBitmap().into(viewItem.image);
Glide.with(this.context).load("http://192.168.211.1/Capstone%202018/FindForMe/Group_Image/"+img+".jpg").asBitmap().into(viewItem.image);
return convertView;
}
public void setYourGroups(ArrayList<your_groups> filteredYourGroups){
this.valueList = filteredYourGroups;
}
@Override
public Filter getFilter() {
if(filterHelper == null){
filterHelper = new YourGroup.FilterHelper(valueList,this,context);
}
return filterHelper;
}
public void refresh(){
notifyDataSetChanged();
}
public void invalidate(){
notifyDataSetInvalidated();
}
class ViewItem {
Integer id;
TextView groupname;
ImageView image;
}
}
your_groups.java
package com.findforme.www.myapplication;
public class your_groups {
public String GroupName;
public Integer id;
public int getId(){
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGroupName(){
return GroupName;
}
public void setGroupName(String GroupName){
this.GroupName = GroupName;
}
}
答案 0 :(得分:0)
请参考此代码并根据您的代码进行更改。.
public class IndexItemAdapter extends RecyclerView.Adapter<IndexItemAdapter.ItemViewHolder> implements Filterable {
private List<UserData> userVoList = new ArrayList<>();
private List<UserData> filterUserVoList = new ArrayList<>();
private Context context;
private String userId;
onItemClickListener onItemClickListener;
public void setOnItemClickListener(IndexItemAdapter.onItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public IndexItemAdapter(Context context, List<UserData> userVoList, String userId) {
this.userVoList = userVoList;
this.context = context;
this.userId = userId;
this.filterUserVoList = userVoList;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
filterUserVoList = userVoList;
} else {
ArrayList<UserData> filteredList = new ArrayList<>();
for (UserData userData : userVoList) {
if (userData.getSubject().toLowerCase().contains(charString) || userData.getName().toLowerCase().contains(charString) || userData.getMessages().toLowerCase().contains(charString)) {
filteredList.add(userData);
}
}
filterUserVoList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filterUserVoList;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
filterUserVoList = (ArrayList<UserData>) filterResults.values;
notifyDataSetChanged();
}
};
}
public interface onItemClickListener {
void onItemClick(UserData userData);
}
@NonNull
@Override
public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.index_row_layout, parent, false);
return new ItemViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
final UserData userData = filterUserVoList.get(position);
holder.tvName.setText(CommonUtils.checkForNullValue(userData.getSubject()));
holder.tvContent.setText(CommonUtils.checkForNullValue(userData.getMessages()));
if (userData.getUserVo() != null) {
holder.tvEmail.setText(userData.getUserVo().getEmail());
Glide.with(context).load(CommonUtils.checkForNullValue(userData.getUserVo().getPhoto())).apply(RequestOptions.circleCropTransform())
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.ALL))
.apply(RequestOptions.placeholderOf(R.drawable.big_user))
.into(holder.ivUserImage);
if (userId.equals(userData.getReceiverId())) {
holder.ivRecivedIcon.setImageResource(R.drawable.forward);
} else {
holder.ivRecivedIcon.setImageResource(R.drawable.reply);
}
}
}
private void changeTextColor(TextView textView, int color) {
textView.setTextColor(color);
}
@Override
public int getItemCount() {
return filterUserVoList.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.irlIvUserImage)
ImageView ivUserImage;
@BindView(R.id.irlTvName)
TextView tvName;
@BindView(R.id.irlTvEmail)
TextView tvEmail;
@BindView(R.id.irlTvDes)
TextView tvContent;
@BindView(R.id.irlTvTime)
TextView tvTime;
@BindView(R.id.irlIvGetImage)
ImageView ivRecivedIcon;
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
并在其中搜索视图。确保您的适配器不为空
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
indexItemAdapter.getFilter().filter(newText.toLowerCase());
indexItemAdapter.notifyDataSetChanged();
return true;
}
});
答案 1 :(得分:0)
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
text_view.setText(adapter.getItem(position - 1) + "");
}
});