我正在开发一个聊天活动,该聊天活动在工具栏中具有搜索视图。我想过滤包含查询的消息,但无法使其正常工作。当我点击搜索按钮时,所有消息均消失。知道我在做什么错吗?
活动:
package com.zen.msy.activity;
import android.app.SearchManager;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.support.v7.widget.SearchView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.zen.msy.R;
import com.zen.msy.adapter.ChatAdapter;
import com.zen.msy.util.Message;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class ChatActivity extends AppCompatActivity {
Toolbar forum_toolbar;
private FirebaseDatabase db;
private DatabaseReference dbRef;
private FirebaseUser fUser;
private ArrayList<Message> chatLists = new ArrayList<>(); //arraylist containing the messages
private ChatAdapter chatAdapter;
private ListView chatList; //listview containing the chat bubbles
private ImageButton floatingActionButton;
private EditText inputChat;
MenuItem searchButton;
SearchView searchView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
forum_toolbar = findViewById(R.id.toolbar);
setSupportActionBar(forum_toolbar);
chatList = findViewById(R.id.chat_list);
inputChat = findViewById(R.id.inputChat);
floatingActionButton = findViewById(R.id.fab);
db = FirebaseDatabase.getInstance();
fUser = FirebaseAuth.getInstance().getCurrentUser();
dbRef = db.getReference("chats");
chatAdapter = new ChatAdapter(getApplicationContext(),fUser,chatLists);
chatList.setAdapter(chatAdapter);
getSupportActionBar().setTitle("Forums");
//Load messages from db
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
chatLists.clear();
for(DataSnapshot ds : dataSnapshot.getChildren()){
Message message = ds.getValue(Message.class);
chatLists.add(message);
// Log.d("VALUE",ds.getValue(Message.class).getText());
}
chatAdapter.notifyDataSetChanged();
scrollMyListViewToBottom();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//When user presses send
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(inputChat.getText().length()>=6){
long msTime = System.currentTimeMillis();
Date curDateTime = new Date(msTime);
// SimpleDateFormat formatter = new SimpleDateFormat("dd'/'MM'/'y hh:mm");
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm");
String dateTime = formatter.format(curDateTime);
//using PATIENT_NAME and PATIENT_MAIL for the message data
Message message = new Message(inputChat.getText().toString(),MainActivity.currentUserName,MainActivity.currentUserMail,dateTime);
dbRef.push().setValue(message);
inputChat.setText("");
InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(inputChat.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}else{
Toast.makeText(getApplicationContext(),"Gönderilecek mesaj uzunluğu en az 6 karakter olmalıdır!",Toast.LENGTH_SHORT).show();
}
}
});
}
private void scrollMyListViewToBottom() {
chatList.post(new Runnable() {
@Override
public void run() {
// Select the last row so it will scroll into view...
chatList.setSelection(chatAdapter.getCount() - 1);
}
});
}
//Inflate the toolbar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar,menu);
MenuItem doneBtn = menu.findItem(R.id.symptomSendButton);
searchButton = menu.findItem(R.id.action_search);
doneBtn.setVisible(false);
searchButton.setVisible(true);
SearchView searchView = (SearchView) searchButton.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
chatAdapter.getFilter().filter(s);
return false;
}
});
return true;
}
}
自定义列表视图的适配器:
package com.zen.msy.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filterable;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseUser;
import com.zen.msy.R;
import com.zen.msy.util.Message;
import android.widget.Filter;
import java.util.ArrayList;
import java.util.List;
public class ChatAdapter extends ArrayAdapter<Message> implements Filterable {
ArrayList<Message> data;
ArrayList<Message> origData;
private FirebaseUser firebaseUser;
public ChatAdapter(Context context, FirebaseUser firebaseUser, ArrayList<Message> chatlist){
super(context, 0, chatlist);
this.firebaseUser = firebaseUser;
this.data = chatlist;
this.origData = new ArrayList<Message>(this.data);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent){
Message message = getItem(position);
// System.out.println("**********UID IS :"+firebaseUser.getUid());
if (firebaseUser.getEmail().equalsIgnoreCase(message.getSenderMail())){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.right_item_layout, parent, false);
TextView txtMessage = convertView.findViewById(R.id.txtMessageRight);
TextView txtTime = convertView.findViewById(R.id.txtTimeRight);
txtMessage.setText(message.getText());
txtTime.setText(message.getTime());
}else{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.left_item_layout, parent, false);
TextView txtUser = convertView.findViewById(R.id.txtUserLeft);
TextView txtMessage = convertView.findViewById(R.id.txtMessageLeft);
TextView txtTime = convertView.findViewById(R.id.txtTimeLeft);
txtUser.setText(message.getSenderName());
txtMessage.setText(message.getText());
txtTime.setText(message.getTime());
}
return convertView;
}
@Override
public Filter getFilter(){
return new Filter(){
@Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if (constraint != null && constraint.toString().length() > 0) {
List<Message> founded = new ArrayList<>();
for(Message item: origData){
if(item.toString().toLowerCase().contains(constraint)){
founded.add(item);
}
}
result.values = founded;
result.count = founded.size();
}else {
result.values = origData;
result.count = origData.size();
}
return result;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
clear();
for (Message item : (List<Message>) results.values) {
add(item);
}
notifyDataSetChanged();
}
};
}
}
工具栏的XML文件:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/symptomSendButton"
android:icon="@drawable/done_icon"
android:title="Send"
app:showAsAction="always"
app:layout_scrollFlags="scroll|enterAlways|snap"
android:visible="false" />
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView" />
</menu>
答案 0 :(得分:0)
您使用空列表创建适配器(因此 origData 是有效的),并在以后添加不更新 origData 的项目。因此,当您进行过滤时,列表为空。
因此,您可以尝试2种方法。
方法1:获取完整的数据列表后,将chatAdapter = new ChatAdapter(getApplicationContext(),fUser,chatLists); chatList.setAdapter(chatAdapter);
移至 onDataChange();
方法2:覆盖适配器的add()和clear()方法,因此它们还会更新 origData 。在过滤器的 publishResults()中,将 clear(), add(item)更改为 data.clear() , data.add(项目)。
希望有帮助!