初始化适配器的正确方法和位置

Correct way and location to initialise adapter

我正在尝试为我的列表视图设置过滤器,但我遇到了这些错误。

Cannot resolve symbol 'myAdapter'

我知道myAdapter还没有初始化,但我不知道我的类需要在哪个里面声明。

error: method setOnQueryTextListener in class SearchView cannot be applied to given types; required: android.support.v7.widget.SearchView.OnQueryTextListener found: android.widget.SearchView.OnQueryTextListener reason: actual argument android.widget.SearchView.OnQueryTextListener cannot be converted to android.support.v7.widget.SearchView.OnQueryTextListener by method invocation conversion

我知道 android.widget.SearchView.OnQueryTextListener 不能转换为 android.support.v7.widget.SearchView.OnQueryTextListener 但我不知道我的代码需要更改什么。我的应用程序使用支持库。我们将不胜感激。

VictoriaLineActivity.java

public class VictoriaLineActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar actionBar = getSupportActionBar();
        //change background colour of action bar
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0098D4")));
        //change text colour of action bar
        actionBar.setTitle(Html.fromHtml("<font color='#FFFFFF'>Victoria line</font>"));

        //enable and show action bar back button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(false);

        FragmentVictoriaLine newFragment = new FragmentVictoriaLine();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.master_container, newFragment);
        transaction.commit();

        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {

        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
        }
    }
}

FragmentVictoriaLine.java

public class FragmentVictoriaLine extends android.support.v4.app.Fragment implements {

    private class Victoria {
        private CharSequence station;
        private CharSequence zone;
        private Class<? extends Activity> activityClass;
        private Class<? extends android.support.v4.app.Fragment> fragmentClass;

        public Victoria(int stationResId, int zoneResId, Class<? extends Activity> activityClass, Class<? extends android.support.v4.app.Fragment> fragmentClass) {
            this.fragmentClass = fragmentClass;
            this.activityClass = activityClass;
            this.station = getResources().getString(stationResId);
            this.zone = getResources().getString(zoneResId);
        }

        @Override
        public String toString() { return station.toString(); }
        public String getzone(){ return zone.toString(); }
    }

    private static Victoria[] mVictoria;

    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    public boolean mTwoPane;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.fragment_victoria_line, container, false);

        if (getActivity().findViewById(R.id.detail_container) != null) {
            mTwoPane = true;
        }else{
            mTwoPane = false;
        }

        // Instantiate the list of stations.
        mVictoria = new Victoria[]{
                new Victoria(R.string.bank, R.string.zone_1, WCBankActivity.class, FragmentWCBank.class),
                new Victoria(R.string.wat, R.string.zone_1, WCWATActivity.class, FragmentWCWAT.class)

        };

        final ListView listView = (ListView)v.findViewById(R.id.list_victoria);
        listView.setAdapter(new MyAdapter(getActivity(), mVictoria));
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        listView.setTextFilterEnabled(true);

        });

        return v;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setHasOptionsMenu(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_victoria_line, menu);

        // Associate searchable configuration with the SearchView
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);

        android.support.v7.widget.SearchView.OnQueryTextListener textChangeListener = new android.support.v7.widget.SearchView.OnQueryTextListener()
        {
            @Override
            public boolean onQueryTextChange(String newText)
            {
                // this is your adapter that will be filtered
                myAdapter.getFilter().filter(newText);
                return true;
            }
            @Override
            public boolean onQueryTextSubmit(String query)
            {
                // this is your adapter that will be filtered
                myAdapter.getFilter().filter(query);
                return true;
            }
        };
        searchView.setOnQueryTextListener(textChangeListener);


        return super.onCreateOptionsMenu(menu);
    }


    static class MyAdapter extends BaseAdapter {

        static class ViewHolder {
            TextView station;
            TextView zone;
        }

        LayoutInflater inflater;
        Victoria[] mVictoria;

        public MyAdapter(Context contexts, Victoria[] samples) {
            this.mVictoria = samples;
            inflater = LayoutInflater.from(contexts);
        }

        @Override
        public int getCount() {
            return mVictoria.length;
        }

        @Override
        public Object getItem(int position) {
            return mVictoria[position];
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.list_item_dualline, null);
                viewHolder = new ViewHolder();

                viewHolder.station = (TextView) convertView.findViewById(R.id.list_item_station);
                viewHolder.zone = (TextView) convertView.findViewById(R.id.list_item_zone);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.station.setText(mVictoria[position].station);
            viewHolder.zone.setText(mVictoria[position].getzone());

            return convertView;
        }
    }
}

你的错误几乎可以告诉你你做错了什么:

Cannot resolve symbol 'myAdapter'

那是因为你还没有声明任何名为myAdapter

的变量

error: method setOnQueryTextListener in class SearchView cannot be applied to given types; required: android.support.v7.widget.SearchView.OnQueryTextListener found: android.widget.SearchView.OnQueryTextListener reason: actual argument android.widget.SearchView.OnQueryTextListener cannot be converted to android.support.v7.widget.SearchView.OnQueryTextListener by method invocation conversion

检查您的导入。您需要使用 android.support.v7.widget.SearchView,但您使用的是标准 SearchView。这应该可以通过简单地导入正确的包来解决。

编辑:

您使用的类型错误OnQueryListener您需要使用支持版本。

编辑 2: 希望这会帮助您入门:

public class FragmentVictoriaLine extends Fragment {
    /**Declare other variables**/

    private MyAdapter myAdapter;

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


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_victoria_line, container, false);

        //Tell the system to call onCreateOptinsMenu
        setHasOptionsMenu(true);
        if (getActivity().findViewById(R.id.detail_container) != null) {
            mTwoPane = true;
        } else {
            mTwoPane = false;
        }

        mVictoria = new Victoria[]{
            new Victoria(R.string.bank, R.string.zone_1, WCBankActivity.class, FragmentWCBank.class),
            new Victoria(R.string.wat, R.string.zone_1, WCWATActivity.class, FragmentWCWAT.class)
        };

        //Declare your adapter here so you can access later
        myAdapter = new MyAdapter(getActivity(), mVictoria);

        final ListView listView = (ListView) v.findViewById(R.id.list_victoria);
        //Set teh adapter here.
        listView.setAdapter(myAdapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        listView.setTextFilterEnabled(true);

        return v;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Inflate the menu items for use in the action bar
        inflater.inflate(R.menu.menu_victoria_line, menu);

        // Associate searchable configuration with the SearchView
        SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
        searchView.setIconifiedByDefault(false);

        SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener()
        {
            @Override
            public boolean onQueryTextChange(String newText)
            {
                // this is your adapter that will be filtered
                myAdapter.getFilter().filter(newText);
                System.out.println("on text chnge text: "+newText);
                return true;
            }
            @Override
            public boolean onQueryTextSubmit(String query)
            {
                // this is your adapter that will be filtered
                myAdapter.getFilter().filter(query);
                System.out.println("on query submit: "+query);
                return true;
            }
        };
        searchView.setOnQueryTextListener(textChangeListener);

    }

   /**....rest of your code*/
}

编辑 3:

这是完整的演示: https://github.com/nak411/AndroidFilterListDemo