Android 如何在同一屏幕中添加两个SimpleCorsorAdapter?

Android 如何在同一屏幕中添加两个SimpleCorsorAdapter?,android,android-studio,android-layout,android-fragments,Android,Android Studio,Android Layout,Android Fragments,我正在创建一个使用两个SearchView组件的屏幕,对于每个组件,我都需要添加建议框(SimpleCursorAdapters)。但是我的建议框面临一个问题,因为它们都连接到在我的XML布局中创建的第一个SearchView 这是我的,这是我的 正如您所看到的,正在“我的调查搜索”下创建“我的网站搜索建议”框 有人知道如何处理建议箱的位置吗 这是my layout.xml: <?xml version="1.0" encoding="utf-8"?

我正在创建一个使用两个SearchView组件的屏幕,对于每个组件,我都需要添加建议框(SimpleCursorAdapters)。但是我的建议框面临一个问题,因为它们都连接到在我的XML布局中创建的第一个SearchView

这是我的,这是我的

正如您所看到的,正在“我的调查搜索”下创建“我的网站搜索建议”框

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

这是my 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组件的片段类:

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]});
            //}
        }
    }
}
导入android.database.Cursor;
导入android.database.MatrixCursor;
导入android.os.Bundle;
导入android.provider.BaseColumns;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.AutoCompleteTextView;
导入android.widget.CursorAdapter;
导入android.widget.ImageView;
导入android.widget.SearchView;
导入android.widget.SimpleCursorAdapter;
导入android.widget.TextView;
导入android.widget.Toast;
导入androidx.core.content.res.ResourcesCompat;
导入androidx.fragment.app.fragment;
导入java.util.array;
导入java.util.Objects;
/**
*创建示例收集器寄存器屏幕片段并处理其行为。
*/
公共类EditSampleFragment扩展了片段{
私有静态最终字符串[]建议={
“a”、“b”};
私有SimpleCursorAdapter SimpleCursorAdapter;
MatrixCursor MatrixCursor;
公共EditSampleFragment(){
//必需的空公共构造函数
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//为该碎片膨胀布局
//保存对片段视图的引用。
视图=充气机。充气(R.layout.fragment\u sample\u View\u layout,container,false);
/*
*创建游标适配器
*/
最终字符串[]from=新字符串[]{“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=新的simpleCursorAdapter(getActivity(),android.R.layout.simple_list_item_1,null,from,to,CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
//处理搜索视图
SearchView siteSearchView=view.findViewById(R.id.site\u search\u view);
SearchView surveySearchView=view.findViewById(R.id.survey\u search\u view);
// ---------------------------------------------------------------------------------------------------------------------------------------
/*
*处理自动完成以获取SearchView的第一个字符。
*/
//获取用于处理搜索屏幕筛选器的AutoCompleteTextView id。
int autoCompleteTextViewID=getResources().getIdentifier(“android:id/search\u src\u text”,null,null);
//开始从第一个字符筛选siteSearchView数据。
AutoCompleteTextView siteSearchAutoCompleteTextView=siteSearchView.findViewById(autoCompleteTextViewID);
siteSearchAutoCompleteTextView.setThreshold(1);
//开始从第一个字符筛选surveySearchView数据。
AutoCompleteTextView surveySearchAutoCompleteTextView=surveySearchView.findViewById(autoCompleteTextViewID);
surveySearchAutoCompleteTextView.setThreshold(1);
// ---------------------------------------------------------------------------------------------------------------------------------------
//设置站点建议适配器。
siteSearchView.SetSuggestionAdapter(simpleCursorAdapter);
//设置调查建议适配器。
surveySearchView.SetSuggestionAdapter(simpleCursorAdapter);
// ---------------------------------------------------------------------------------------------------------------------------------------
//更改文本字体
int siteTextId=siteSearchView.getContext().getResources().getIdentifier(“android:id/search\u src\u text”,null,null);
TextView siteSearchText=siteSearchView.findViewById(siteTextId);
setTypeface(ResourcesCompat.getFont(Objects.requireNonNull(getContext()),R.font.roboto_light));
int surveyTextId=surveySearchView.getContext().getResources().getIdentifier(“android:id/search\u src\u text”,null,null);
TextView surveySearchText=surveySearchView.findViewById(surveyTextId);
surveySearchText.setTypeface(ResourcesCompat.getFont(getContext(),R.font.roboto_light));
// ---------------------------------------------------------------------------------------------------------------------------------------
//更改两侧的放大镜。
int siteMagnifierId=getResources().getIdentifier(“android:id/search\u mag\u icon”,null,null);
ImageView SiteSearch放大镜=siteSearchView.findViewById(Site放大镜ID);
ViewGroup siteLinearLayoutSearchView=(ViewGroup)SiteSearchMagnizer.getParent();
//从左边移除它。。。
siteLinearLayoutSearchView.removeView(SiteSearch放大镜);
//然后将其放回(默认为右侧)
siteLinearLayoutSearchView.addView(SiteSearch放大镜);
//确保已实例化Search放大镜。(如果需要,请在此进行分析)
如果(SiteSearchMagnizer.getParent()!=null){
((ViewGroup)SiteSearchMagnizer.getParent()).removeView(SiteSearchMagnizer);
}
int surveyMagnifierId=getResources().getIdentifier(“android:id/search\u mag\u icon”,null,null);
ImageView SurveySearch放大镜=surveySearchView.findViewById(surveyMagnifierId);