如何在同一屏幕上添加两个SimpleCursorAdapter?

时间:2020-09-23 13:52:45

标签: android android-studio android-layout android-fragments

我正在创建一个使用两个SearchView组件的屏幕,我需要为每个组件添加建议框(SimpleCursorAdapters)。但是我的建议框遇到了问题,因为这两个提示框都已附加到在我的XML布局中创建的第一个SearchView中。

这是我的Survey Search,这是我的Site Search

您会看到我的“问卷调查”下正在创建“网站搜索”建议框。

有人知道如何处理建议框的位置吗?

这是我的layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
    
    <SearchView
        android:id="@+id/survey_search_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="44dp"
        android:background="@drawable/search_box_border"
        android:clickable="true"
        android:iconifiedByDefault="false"
        android:layoutDirection="rtl"
        android:queryHint="Search Survey Here"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="0dp" />

    <SearchView
        android:id="@+id/site_search_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="176dp"
        android:background="@drawable/search_box_border"
        android:clickable="true"
        android:iconifiedByDefault="false"
        android:layoutDirection="rtl"
        android:queryHint="Search Site Here"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="0dp">
    </SearchView>

</androidx.constraintlayout.widget.ConstraintLayout>

这是我处理SearchView组件的Fragment类:

import android.database.Cursor;
import android.database.MatrixCursor;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;

import java.util.Arrays;
import java.util.Objects;

/**
 * Create the Sample Collector Register screen fragment and handles its behavior.
 */
public class EditSampleFragment extends Fragment {

    private static final String[] SUGGESTIONS = {
            "a", "b"};

    private SimpleCursorAdapter simpleCursorAdapter;

    MatrixCursor matrixCursor;

    public EditSampleFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        // Holds a reference to the Fragments's View.
        View view = inflater.inflate(R.layout.fragment_sample_view_layout, container, false);

        /*
         * Creates the CursorAdapter
         */
        final String[] from = new String[]{"sampleName"};
        Toast.makeText(getContext(), "from -> " + Arrays.toString(from), Toast.LENGTH_SHORT).show();
        final int[] to = new int[]{android.R.id.text1};
        Toast.makeText(getContext(), "to -> " + Arrays.toString(to), Toast.LENGTH_SHORT).show();

        simpleCursorAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1, null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        // Handles the SearchViews
        SearchView siteSearchView = view.findViewById(R.id.site_search_view);
        SearchView surveySearchView = view.findViewById(R.id.survey_search_view);

// ---------------------------------------------------------------------------------------------------------------------------------------
        /*
         *  Handles the autoComplete to get the first character of the SearchView.
         */

        // Gets the AutoCompleteTextView id to handle the search screen filter.
        int autoCompleteTextViewID = getResources().getIdentifier("android:id/search_src_text", null, null);

        // Starts to filter the siteSearchView data from the first character.
        AutoCompleteTextView siteSearchAutoCompleteTextView = siteSearchView.findViewById(autoCompleteTextViewID);
        siteSearchAutoCompleteTextView.setThreshold(1);

        // Starts to filter the surveySearchView data from the first character.
        AutoCompleteTextView surveySearchAutoCompleteTextView = surveySearchView.findViewById(autoCompleteTextViewID);
        surveySearchAutoCompleteTextView.setThreshold(1);

// ---------------------------------------------------------------------------------------------------------------------------------------

        // Sets the site suggestion adapter.
        siteSearchView.setSuggestionsAdapter(simpleCursorAdapter);

        // Sets the survey suggestion adapter.
        surveySearchView.setSuggestionsAdapter(simpleCursorAdapter);

// ---------------------------------------------------------------------------------------------------------------------------------------
        // Changes the text font
        int siteTextId = siteSearchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        TextView siteSearchText = siteSearchView.findViewById(siteTextId);

        siteSearchText.setTypeface(ResourcesCompat.getFont(Objects.requireNonNull(getContext()), R.font.roboto_light));

        int surveyTextId = surveySearchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        TextView surveySearchText = surveySearchView.findViewById(surveyTextId);

        surveySearchText.setTypeface(ResourcesCompat.getFont(getContext(), R.font.roboto_light));

// ---------------------------------------------------------------------------------------------------------------------------------------
        // Changes both magnifiers side.
        int siteMagnifierId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
        ImageView siteSearchMagnifier = siteSearchView.findViewById(siteMagnifierId);

        ViewGroup siteLinearLayoutSearchView = (ViewGroup) siteSearchMagnifier.getParent();
        //Remove it from the left...
        siteLinearLayoutSearchView.removeView(siteSearchMagnifier);
        //then put it back (to the right by default)
        siteLinearLayoutSearchView.addView(siteSearchMagnifier);

        // To ensure that the searchMagnifier has been instantiated. (Analyse if it is needed here)
        if (siteSearchMagnifier.getParent() != null) {
            ((ViewGroup) siteSearchMagnifier.getParent()).removeView(siteSearchMagnifier);
        }

        int surveyMagnifierId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
        ImageView surveySearchMagnifier = surveySearchView.findViewById(surveyMagnifierId);

        ViewGroup surveyLinearLayoutSearchView = (ViewGroup) surveySearchMagnifier.getParent();
        //Remove it from the left...
        surveyLinearLayoutSearchView.removeView(surveySearchMagnifier);
        //then put it back (to the right by default)
        surveyLinearLayoutSearchView.addView(surveySearchMagnifier);

        // To ensure that the searchMagnifier has been instantiated.
        if (surveySearchMagnifier.getParent() != null) {
            ((ViewGroup) surveySearchMagnifier.getParent()).removeView(surveySearchMagnifier);
        }

// ---------------------------------------------------------------------------------------------------------------------------------------

        siteSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String querySite) {
                if (querySite.isEmpty()) {
                    siteLinearLayoutSearchView.addView(siteSearchMagnifier);
                } else {
                    siteLinearLayoutSearchView.removeView(siteSearchMagnifier);
                }
                simpleCursorAdapter.changeCursor(matrixCursor);
                populateAdapter(querySite);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String querySite) {
                if (querySite.isEmpty()) {
                    siteLinearLayoutSearchView.addView(siteSearchMagnifier);
                } else {
                    siteLinearLayoutSearchView.removeView(siteSearchMagnifier);
                }

                populateAdapter(querySite);
                simpleCursorAdapter.changeCursor(matrixCursor);

                return false;
            }
        });

        siteSearchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
            @Override
            public boolean onSuggestionSelect(int position) {
                // TODO
                return true;

            }

            @Override
            public boolean onSuggestionClick(int position) {
                Toast.makeText(getContext(), "Site click", Toast.LENGTH_SHORT).show();
                Cursor cursor = (Cursor) simpleCursorAdapter.getItem(position);
                String txt = cursor.getString(cursor.getColumnIndex("sampleName"));
                siteSearchView.setQuery(txt, true);
                return false;
            }
        });

        surveySearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String querySurvey) {
                if (querySurvey.isEmpty()) {
                    surveyLinearLayoutSearchView.addView(surveySearchMagnifier);
                } else {
                    surveyLinearLayoutSearchView.removeView(surveySearchMagnifier);
                }
                simpleCursorAdapter.changeCursor(matrixCursor);
                populateAdapter(querySurvey);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String querySurvey) {
                if (querySurvey.isEmpty()) {
                    surveyLinearLayoutSearchView.addView(surveySearchMagnifier);
                } else {
                    surveyLinearLayoutSearchView.removeView(surveySearchMagnifier);
                }
                populateAdapter(querySurvey);
                simpleCursorAdapter.changeCursor(matrixCursor);
                return false;
            }
        });

        surveySearchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
            @Override
            public boolean onSuggestionSelect(int position) {
                // TODO
                return true;

            }

            @Override
            public boolean onSuggestionClick(int position) {
                Toast.makeText(getContext(), "Survey click", Toast.LENGTH_SHORT).show();
                Cursor cursor = (Cursor) simpleCursorAdapter.getItem(position);
                String txt = cursor.getString(cursor.getColumnIndex("sampleName"));
                surveySearchView.setQuery(txt, true);
                return false;
            }
        });

        return view;
    }

    private void populateAdapter(String query) {
        matrixCursor = new MatrixCursor(new String[]{BaseColumns._ID, "sampleName"});

        for (int i = 0; i < SUGGESTIONS.length; i++) {
            //if (SUGGESTIONS[i].toLowerCase().startsWith(query.toLowerCase())) {
            matrixCursor.addRow(new Object[]{i, SUGGESTIONS[i]});
            //}
        }
    }
}

有人知道我在做什么错或如何处理这种行为吗?

非常感谢!

0 个答案:

没有答案