自定义Listview + Xmlparser + Actionbar 4.2 Sherlock Searchview

时间:2012-12-28 14:37:03

标签: android search xml-parsing actionbarsherlock android-listfragment

我有一个自定义ListView,通过传递xml数据ArrayList来获取baseadapter。

我想使用ActionbarSherlock 4.2 Searchview执行搜索,因此在用户放置文本并按下按钮后,它会使结果膨胀新的布局。

最佳指南是什么?

  • 我应该在BaseAdapter上实现Filterable吗?如果是,我如何从Sherlock Searchview而不是filterText.addTextChangedListener(filterTextWatcher)获取tostring();?
  • 我应该创建一个新的BaseAdapter来仅下载搜索的listview提示吗?如果是,您是否有任何样本或教程可以链接?
  • 还是其他任何方式?

自定义列表视图:

public class CustomizedListView extends ListFragment {
    // All static variables
    static final String URL = "http://api.androidhive.info/music/music.xml";
    // XML node keys
    static final String KEY_SONG = "song"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_ARTIST = "artist";
    static final String KEY_DURATION = "duration";
    static final String KEY_THUMB_URL = "thumb_url";

    ListView list;
    LazyAdapter adapter;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);


        ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_SONG);
        // looping through all song nodes <song>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
            map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
            map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

            // adding HashList to ArrayList
            songsList.add(map);
        }



        // Getting adapter by passing xml data ArrayList
        adapter = new LazyAdapter(getActivity(), songsList);        
        setListAdapter(adapter);



    }   
}

BaseAdapter:

public class LazyAdapter extends BaseAdapter {

    private FragmentActivity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader; 


    public LazyAdapter(FragmentActivity fragmentActivity, ArrayList<HashMap<String, String>> d) {
        activity = fragmentActivity;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

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

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)

            vi = inflater.inflate(R.layout.list_row, null);

        TextView title = (TextView)vi.findViewById(R.id.title); // title
        TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
        TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
        ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

        HashMap<String, String> song = new HashMap<String, String>();
        song = data.get(position);

        // Setting all values in listview
        title.setText(song.get(CustomizedListView.KEY_TITLE));
        artist.setText(song.get(CustomizedListView.KEY_ARTIST));
        duration.setText(song.get(CustomizedListView.KEY_DURATION));
        imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
        return vi;
    }
}

Sherlock ActionBar SearchView:

public abstract class BaseSampleActivity extends SherlockFragmentActivity {
    private static final Random RANDOM = new Random();

    TestFragmentAdapter mAdapter;
    ViewPager mPager;
    PageIndicator mIndicator;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
         SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
        searchView.setQueryHint("Procure pelo nome");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String query) {
            // TODO Auto-generated method stub
            Intent search = new Intent(getApplicationContext(), SearchableActivity.class);
            search.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            search.putExtra(query, query);
            startActivityForResult(search, 0);
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            // TODO Auto-generated method stub
            return false;
        }
    });

        menu.add("Search")
            .setIcon(R.drawable.ic_search_inverse)
            .setActionView(searchView)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
        return true;
    }

NewActivity:

public class SearchableActivity extends SherlockListActivity{

    // All static variables
        static final String URL = "http://api.androidhive.info/music/music.xml";
        // XML node keys
        static final String KEY_SONG = "song"; // parent node
        static final String KEY_ID = "id";
        static final String KEY_TITLE = "title";
        static final String KEY_ARTIST = "artist";
        static final String KEY_DURATION = "duration";
        static final String KEY_THUMB_URL = "thumb_url";

    private String message;
    private ListView list;
    private LazyAdapterS adapter;

    protected void onCreate(Bundle savedInstanceState, String query) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        message = getIntent().getExtras().getString(query);
        setContentView(R.layout.main_list_row);


        ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_SONG);
        // looping through all song nodes <song>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
            map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
            map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

            // adding HashList to ArrayList
            songsList.add(map);
        }


        list=(ListView)findViewById(R.id.list);

        // Getting adapter by passing xml data ArrayList
        adapter = new LazyAdapterS(this, songsList);        
        list.setAdapter(adapter);
        ((Filterable) list.getAdapter()).Filter(message);// Error The method Filter(String) is undefined for the type Filterable
    }

}

更新:我把setOnQueryTextListener作为@Luksprog的建议。 更新:我创建了一个新的活动来显示搜索结果,但仍然在过滤器上出错,我不知道如何处理。

谢谢,

1 个答案:

答案 0 :(得分:0)

  

我应该在BaseAdapter上实现Filterable吗?

如果要对适配器(任何Android SDK适配器都使用)使用标准过滤机制,是的,您需要实现Filterable接口,并为它的两种方法提供正确的实现。

  

如果是,我如何从Sherlock Searchview获取tostring()   而不是filterText.addTextChangedListener(filterTextWatcher);?

查看OnQueryTextListener

public boolean onQueryTextSubmit(String query) {
      ((Filterable) listview.getAdapter()).filter(query);
      return true;
}
  

我应该创建一个新的BaseAdapter来仅下载listview提示   通过搜索?如果是,您是否有任何样本或教程可以链接?

如果你的意思是,再次解析xml(仅使用与查询字符串匹配的内容)并创建一个新的适配器来显示结果,不,因为你将做很多不必要的工作(特别是你所做的所有网络调用)应该真的尝试移动后台线程。)

如果您想在新活动中显示结果,请将查询String放入启动结果活动的Intent中,然后在那里执行/重做过滤。

  

还是其他任何方式?

见第一点。