如何添加搜索编辑文本和列表视图?

时间:2018-03-12 04:51:57

标签: android listview android-edittext android-adapter searchview

我有一个列表视图和一个EditText。当我在EditText上写字时,我想显示我的列表视图从这些字母表开始。我正在为我的列表视图添加自定义适配器。

我对getFilter()

中的Edittext.addTextChangedListener有疑问

我的XML布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="0dp"
    android:paddingBottom="0dp"
    tools:context=".menuucare.birthday.BirthdayActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_birthday"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay"
            app:layout_scrollFlags="scroll|enterAlways">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar_birthday"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/AppTheme.PopupOverlay"
                app:contentInsetLeft="0dp"
                app:contentInsetStart="10dp"
                app:layout_scrollFlags="scroll|enterAlways"
                app:layout_collapseMode="pin">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:gravity="center|left">

                        <Button
                            android:id="@+id/back_birthday"
                            android:layout_width="30dp"
                            android:layout_height="30dp"
                            android:background="@drawable/back"/>

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:layout_weight="6"
                        android:gravity="right"
                        android:layout_marginLeft="10dp"
                        android:layout_marginRight="10dp"
                        android:layout_gravity="center">

                        <EditText
                            android:id="@+id/search_birth"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:hint="Search here..."
                            android:drawableRight="@drawable/ic_search_white_24dp"/>

                    </LinearLayout>

                </LinearLayout>

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        android:layout_height="match_parent"
        android:layout_below="@id/linearLayout9"/>


</android.support.design.widget.CoordinatorLayout>

BirthdayActivity.java

    public class BirthdayActivity extends ListActivity {

    private final DateFormatSymbols dateSymbols = new DateFormatSymbols();
    private Database db;
    private Button back_birthday;
    private ListView birthday;
    private TextView teks;
    private EditText search_birth;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_birthday);
        getListView().setFastScrollEnabled(true);
        this.db = new Database(getContentResolver());
        // debug code
        // Debug.logDatabase(this);

        // start BirthdayBroadcastReceiver if it is activated
        Preferences prefs = Preferences.getInstance(getApplicationContext());
        if (prefs.getActivateService()) {
            BirthdayBroadcastReceiver.restart(getApplicationContext());
        }

        search_birth = (EditText) findViewById(R.id.search_birth);

        back_birthday = findViewById(R.id.back_birthday);
        back_birthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BirthdayActivity.super.onBackPressed();
                finish();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();

        updateView();
    }

    private void updateView() {

        // create new list adapter
        final ListView ls = getListView();
        final MultiListAdapter listAdapter = new MultiListAdapter();
        final List<ListAdapter> adapterList = listAdapter.getListAdapters();
        ls.setDivider(this.getResources().getDrawable(R.drawable.transparent));
        ls.setDividerHeight(20);

        ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<Intent> targetShareIntents=new ArrayList<Intent>();
                Intent shareIntent=new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.setType("text/plain");
                List<ResolveInfo> resInfos=getPackageManager().queryIntentActivities(shareIntent, 0);
                if(!resInfos.isEmpty()) {
                    System.out.println("Have package");
                    for (ResolveInfo resInfo : resInfos) {
                        String packageName = resInfo.activityInfo.packageName;
                        Log.i("Package Name", packageName);
                        if (packageName.contains("com.twitter.android") || packageName.contains("com.facebook.katana") ||
                                packageName.contains("com.whatsapp") || packageName.contains("com.google.android.apps.plus") ||
                                packageName.contains("com.google.android.gm")|| packageName.contains("com.yahoo.mobile") ||
                                packageName.contains("com.android.mms")|| packageName.contains("com.linkedin.android")||
                                packageName.contains("com.google.android.apps.messaging")|| packageName.contains("jp.naver.line.android")){
                            Intent intent = new Intent();
                            intent.setComponent(new ComponentName(packageName, resInfo.activityInfo.name));
                            intent.setAction(Intent.ACTION_SEND);
                            intent.setType("text/plain");
                            intent.putExtra(Intent.EXTRA_TEXT, "Have the most happy and unforgettable birthday.\n\n - MemoMoo Apps -");
                            intent.putExtra(Intent.EXTRA_SUBJECT, "Birthday Card");
                            intent.setPackage(packageName);
                            targetShareIntents.add(intent);
                        }
                    }
                    if (!targetShareIntents.isEmpty()) {
                        System.out.println("Have Intent");
                        Intent chooserIntent = Intent.createChooser(targetShareIntents.remove(0), "Choose app to share");
                        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetShareIntents.toArray(new Parcelable[]{}));
                        startActivity(chooserIntent);
                    } else {
                        System.out.println("Do not Have Intent");
                        // showDialaog(this);
                    }
                }

             /*   Intent sendIntent = new Intent(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, "Have the most happy and unforgettable birthday.\n\n - UCare Apps -");
                sendIntent.setType("text/");
                startActivity(sendIntent);*/
                }
        });

        // load birthday and contact information
        List<Contact> contacts = this.db.getAllContacts();
        List<BirthContact> birthContacts = BirthContactHelper.createBirthContactList(contacts);

        // group all contacts by known and unknown birthday
        SortedSet<BirthContact> knownBirthdays = new TreeSet(new BirthContactBirthdayComparator());

        for (BirthContact birthContact : birthContacts) {
            DateOfBirth dateOfBirth = birthContact.getDateOfBirth();

            if (dateOfBirth != null) {
                knownBirthdays.add(birthContact);
            }
        }

        Integer currentMonth = null;
        BirthdayContactAdapter currentBirthdayContactAdapter = null;
        String[] monthStrs = this.dateSymbols.getMonths();
        for (BirthContact birthContact : knownBirthdays) {
            int month = birthContact.getDateOfBirth().getDate().get(Calendar.MONTH);


                if (currentMonth == null || currentMonth != month) {
                    currentMonth = month;

                    currentBirthdayContactAdapter = new BirthdayContactAdapter(this);
                    adapterList.add(new CategoryAdapter(this, monthStrs[currentMonth]));
                    adapterList.add(currentBirthdayContactAdapter);

                }

                currentBirthdayContactAdapter.add(birthContact);

        }
        setListAdapter(listAdapter);

        search_birth.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                listAdapter.getFilter().filter(s);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    public void onBackPressed () {
        BirthdayActivity.super.onBackPressed();
        finish();
    }

}

BirthdayContactAdapter.java

    public class BirthdayContactAdapter extends ArrayAdapter<BirthContact> implements Filterable {
    private Typeface birthdaytextstyle;
    private TextView BirthdayTextStyle;
    private final Calendar today;
    private final LayoutInflater inflater;
    private final Resources res;
    private CardView card;
    private ArrayList<ListAdapter> data;

    public BirthdayContactAdapter(Context context) {
        super(context, R.layout.listviewbirthday);
        this.today = CalendarUtils.todaysCalendar();
        this.inflater = LayoutInflater.from(context);
        this.res = context.getResources();
    }

    public BirthdayContactAdapter(Context context, Collection<BirthContact> birthContacts) {
        this(context);
        for (BirthContact birthContact : birthContacts) {
            add(birthContact);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public View getView(int position, View view, ViewGroup parent) {

        // create view if needed
        if (view == null) {
            view = this.inflater.inflate(R.layout.listviewbirthday, null);
        }

        birthdaytextstyle = TextSettingActivity.typefacestyle;
        if(birthdaytextstyle != null){
            BirthdayTextStyle = (TextView)view.findViewById(R.id.name);
            BirthdayTextStyle.setTypeface(birthdaytextstyle);}

        // set name
        BirthContact birthContact = getItem(position);
        TextView name = (TextView) view.findViewById(R.id.name);
        String username = birthContact.getContact().getName();
        String Name = username + "'s Birthday is near, lets celebrate this wonderful moment!";
        name.setText(Name);

        // set dateOfBirth if available
        if (birthContact.getDateOfBirth() != null) {
            DateOfBirth dateOfBirth = birthContact.getDateOfBirth();

            Calendar date = dateOfBirth.getDate();
            Calendar nextBirthday = CalendarUtils.nextBirthday(today, date);
            int days = CalendarUtils.timeSpanInDays(today, nextBirthday);
            int newAge = nextBirthday.get(Calendar.YEAR) - date.get(Calendar.YEAR);

            TextView info = (TextView) view.findViewById(R.id.info);
            info.setText(getBirthdayText(days, newAge));

            if (days == 0){

                /*Intent intent = new Intent(getContext(), BirthdayActivity.class);
                PendingIntent pIntent = PendingIntent.getActivity(getContext(), (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

                Notification n = new Notification.Builder(getContext())
                        .setContentTitle(birthContact.getContact().getName() +" Tomorrow Birthday")
                        .setContentText("Celebrate and say something ")
                        .setSmallIcon(R.mipmap.ucare_icon_app)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setContentIntent(pIntent)
                        .build();

                NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(0, n);*/

                Intent intent = new Intent(getContext(), AlarmReceiveBirth.class);
                final PendingIntent pIntent = PendingIntent.getBroadcast(getContext(),(int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

                // create an alarm
                AlarmManager alarm = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);

                // set tomorrow at midnight
                Calendar cal = Calendar.getInstance();
                //cal.add(Calendar.DAY_OF_YEAR, 0);
                cal.set(Calendar.HOUR_OF_DAY, 1);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 1);

                // trigger alarm
                alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pIntent);

            } if( days == 1) {

                //Intent intent = new Intent(getContext(), BirthdayActivity.class);
                //PendingIntent pIntent = PendingIntent.getActivity(getContext(), (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

                Notification n = new Notification.Builder(getContext())
                        .setContentTitle(birthContact.getContact().getName() +" Tomorrow Birthday")
                        .setContentText("We Will Remind You Tomorrow")
                        .setSmallIcon(R.mipmap.ucare_icon_app)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        //.setContentIntent(pIntent)
                        .build();

                NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(0, n);

            }else {

                Intent intent = new Intent(getContext(), AlarmReceiveBirth.class);
                final PendingIntent pIntent = PendingIntent.getBroadcast(getContext(), (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
                AlarmManager alarm = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
                alarm.cancel(pIntent);
            }
        }

        return view;
    }


    private String getBirthdayText(int days, int newAge) {
        String text;
        switch (days) {
        case 0:
            text = String.format(res.getString(R.string.summary_today), newAge);
            break;
        case 1:
            text = String.format(res.getString(R.string.summary_tomorrow), newAge);
            break;
        default:
            text = String.format(res.getString(R.string.summary_other), days, newAge);
        }
        return text;
    }
}

BirthContact.java

    public class BirthContact {

    private final Contact contact;
    private final DateOfBirth dateOfBirth;


    public BirthContact(Contact contact, DateOfBirth dateOfBirth) {
        super();

        this.contact = contact;
        this.dateOfBirth = dateOfBirth;
    }

    public Contact getContact() {
        return contact;
    }

    public DateOfBirth getDateOfBirth() {
        return dateOfBirth;
    }


    @Override
    public String toString() {
        if (this.dateOfBirth != null) {
            return String.format("%s (%s)", this.contact.getName(), this.getDateOfBirth().getDate());
        }
        return this.contact.getName();
    }
}

MultiListAdapter.java

    public class MultiListAdapter extends BaseAdapter {

    private final List<ListAdapter> listAdapters = new ArrayList<ListAdapter>();

    public List<ListAdapter> getListAdapters() {
        return listAdapters;
    }

    @Override
    public int getCount() {
        int count = 0;
        for (ListAdapter listAdapter : this.listAdapters) {
            count += listAdapter.getCount();
        }
        return count;
    }

    @Override
    public Object getItem(int position) {
        int positionOffset = 0;
        for (ListAdapter listAdapter : this.listAdapters) {
            if (position - positionOffset < listAdapter.getCount()) {
                return listAdapter.getItem(position - positionOffset);
            }
            positionOffset += listAdapter.getCount();
        }
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int positionOffset = 0;
        for (ListAdapter listAdapter : this.listAdapters) {
            if (position - positionOffset < listAdapter.getCount()) {
                return listAdapter.getView(position - positionOffset, convertView, parent);
            }
            positionOffset += listAdapter.getCount();
        }
        return null;
    }

    @Override
    public int getViewTypeCount() {
        int viewTypeCount = 0;
        for (ListAdapter listAdapter : this.listAdapters) {
            viewTypeCount += listAdapter.getViewTypeCount();
        }
        // viewTypeCount may not be 0
        if (viewTypeCount == 0) {
            return 1;
        }
        return viewTypeCount;
    }

    @Override
    public int getItemViewType(int position) {
        int positionOffset = 0;
        int typeOffset = 0;
        for (ListAdapter listAdapter : this.listAdapters) {
            if (position - positionOffset < listAdapter.getCount()) {
                return typeOffset + listAdapter.getItemViewType(position - positionOffset);
            }
            positionOffset += listAdapter.getCount();
            typeOffset += listAdapter.getViewTypeCount();
        }
        return -1;
    }

    @Override
    public boolean areAllItemsEnabled() {
        return false;
    }

    @Override
    public boolean isEnabled(int position) {
        int positionOffset = 0;
        for (ListAdapter listAdapter : this.listAdapters) {
            if (position - positionOffset < listAdapter.getCount()) {
                return listAdapter.isEnabled(position - positionOffset);
            }
            positionOffset += listAdapter.getCount();
        }
        return false;
    }

}

3 个答案:

答案 0 :(得分:0)

在适配器类中使用适配器类进行一些更改我在您实现定义数据需求时将假设的生日数据放入。喜欢 BirthdayContactAdapter.java将代码放在里面。

 private List<BirthContact> mBirthContactFilter = new ArrayList<>();
private CustomFilter mFilter;

public BirthdayContactAdapter(Context context, List<BirthContact> mContactList) {
    super(context, R.layout.listviewbirthday);
    this.today = CalendarUtils.todaysCalendar();
    this.inflater = LayoutInflater.from(context);
    this.res = context.getResources();
    this.mBirthContactFilter = mContactList;
    mFilter = new CustomFilter();
}

@Override
public Filter getFilter() {
    return mFilter;
}

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

/**
 * this class for filter data.
 */
class CustomFilter extends Filter {

    @Override
    protected FilterResults performFiltering(CharSequence charSequence) {
        FilterResults results = new FilterResults();
        if (charSequence != null && charSequence.length() > 0) {
            ArrayList<BirthContact> filters = new ArrayList<>();
            charSequence = charSequence.toString().toUpperCase();
            for (int i = 0; i < mBirthContactList.size(); i++) { // actual list to bind
                if (mBirthContactList.get(i).getUserName().toUpperCase().contains(charSequence) || mContactList.get(i).getUserEmail().toUpperCase().contains(charSequence)) { // if you bind birthday boy name that.
                    BirthContact contact = new BirthContact();
                    contact.setName(mBirthContactList.get(i).getName()); // hear write your data to add filter define in pojo class.
                    contact.setAge(mBirthContactList.get(i).getAge());
                    filters.add(contact);

                }
            }
            results.count = filters.size();
            results.values = filters;

        } else {
            results.count = mBirthContactList.size();
            results.values = mBirthContactList;
        }
        return results;
    }

    @Override
    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
        mBirthContactFilter = (ArrayList<BirthContact>) filterResults.values;
        notifyDataSetChanged();
    }
}

答案 1 :(得分:0)

最简单的方法。在listview之前添加editext。

search_birth.addTextChangedListener(new TextWatcher() {


            @Override
            public void onTextChanged(CharSequence charText, int arg1, int arg2, int arg3) {
                List<BirthContact> arrtL_temp_one = new ArrayList<>();

            chars = chars.toString().toLowerCase();
            if (arrtL_temp_one.size() > 0)
                arrtL_temp_one.clear();
            if (chars.length() == 0) {
                arrtL_temp_one.addAll(birthContacts);
            } else {
                for (int listNo = 0; listNo < birthContacts.size(); listNo++) {
                    if (birthContacts.get(listNo).getFoodName().toLowerCase().contains(chars)) {
                        BirthContact contact = new BirthContact();
                        contact.setName(birthContacts.get(listNo).getName()); // hear write your data to add filter define in pojo class.
                        contact.setAge(birthContacts.get(listNo).getAge());

                        arrtL_temp_one.add(contact);

                    }
                }
            }
                birthdayContactAdapter= new BirthdayContactAdapter(getActivity(), arrtL_temp_one);
                birthday.setAdapter(birthdayContactAdapter);


            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {

                // TODO Auto-generated method stub
            }
        });

答案 2 :(得分:0)

在ListActivity中,键入一个字母时,将调用addTextChangedListener。

 search_birth.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            listAdapter.filter(s); //*just create a method in the adapter ie.public void filter(String s)*
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

创建一个新的arraylist newBirthContact并将originalBirthContact添加到newBirthContact

private List<BirthContact> newBirthContact = new ArrayList<>();

private List<BirthContact> originalBirthContact= new ArrayList<>();

public BirthdayContactAdapter(Context context, List<BirthContact> originalBirthContact) 
{
      this.originalBirthContact= originalBirthContact;
      this.newBirthContact.addAll(originalBirthContact);

}

在适配器

中创建方法过滤器(String s)
 public void filter(String s) {

        for (BirthContact mBirthContact : newBirthContact)
            {
              if(mBirthContact.getName()().toString().toLowerCase().contains(s.toString().toLowerCase()))
                {
                    originalBirthContact.add(mBirthContact);
                }
            }

        notifyDataSetChanged();

}