Как выполнить поиск в расширяемом списке, который находится во фрагменте?

Вот в чем дело..

У меня есть одно действие, в котором я реализовал ActionBarSherlock, View Pager с навигацией по вкладкам.

В панели действий я разместил представление поиска. Теперь я добавляю список фрагментов из действия, используя viewPagerAdapter.

Теперь во фрагментах я разместил расширяемый список и отображаю продукты с именем раздела в расширяемом списке.

Чем я хочу заниматься ::

Я хочу выполнить поиск продуктов из расширяемого списка.

Проблема, с которой я столкнулся ::

Я поместил представление поиска в действие, из которого я вызываю разные фрагменты. Итак, как выполнить поиск???

Мой код ::

Активность ::

public class Activity extends SherlockFragmentActivity  implements TabListener,SearchView.OnQueryTextListener,SearchView.OnSuggestionListener
{
    TabHost tabHost;
    TabHost.TabSpec spec;
    Intent intent; 
    Resources res;
    Context mContext;
    ProgressDialog pd=null;
    Handler handler=new Handler();
    MD5Generator md5Generator=new MD5Generator();
    HttpConn httpConn=new HttpConn();
    MyAccountInfo myAccountInfo;
    private UserInfo userInfo=new UserInfo();
    private Calendar cal = Calendar.getInstance();
    private AppPreferences preference;
    ArrayList<String> menuInfo;
    //private ActionBar actionBar;
    private ActionBarTabMenuAdapter actionbartabmenuAdapter;
    private ViewPager awesomePager;
    DataHelper dataHelper;

    ArrayList<Integer> servicesImage;
    ArrayList<String> servicesName;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final ActionBar actionBar=getSupportActionBar();
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        mContext=this;

        //      getSupportActionBar().setStackedBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.white)));
        //      getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        //      getSupportActionBar().setDisplayUseLogoEnabled(false);
        //      getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header_color)));  

        awesomePager = (ViewPager) findViewById(R.id.awesomepager);

        dataHelper=new DataHelper(this);
        menuInfo=dataHelper.getTransMenuInfo();

        servicesName = new ArrayList<String>();
        servicesImage = new ArrayList<Integer>();

        if(menuInfo.contains("1"))
        {
            servicesName.add(dataHelper.getTransMenu_ModuleName("1"));
            servicesImage.add(R.drawable.abs__ic_search);
        }
        if(menuInfo.contains("2"))
        {
            servicesName.add(dataHelper.getTransMenu_ModuleName("2"));
            servicesImage.add(R.drawable.abs__ic_search);
        }
        if(menuInfo.contains("4"))
        {
            servicesName.add(dataHelper.getTransMenu_ModuleName("4"));
            servicesImage.add(R.drawable.abs__ic_search);
        }


        dataHelper.close();
        servicesName.add("My Account");
        servicesImage.add(R.drawable.abs__ic_search);
        menuInfo.add("myacc");

        servicesName.add("Reports");
        servicesImage.add(R.drawable.abs__ic_search);
        menuInfo.add("Reports");

        servicesName.add("Settings");
        servicesImage.add(R.drawable.abs__ic_search);
        menuInfo.add("Settings");

        List<Fragment> fragments = getFragments();

        actionbartabmenuAdapter = new ActionBarTabMenuAdapter(getSupportFragmentManager(), fragments,this,servicesName,servicesImage);
        awesomePager.setAdapter(actionbartabmenuAdapter);
        System.out.println(" ****  Selected Item==>"+awesomePager.getCurrentItem());

        awesomePager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);

            }
        });

        for (int i = 0; i < actionbartabmenuAdapter.getCount(); i++) {
            Tab tab = actionBar.newTab();
            //tab.setText(awesomeAdapter.getPageTitle(i));
            tab.setText(servicesName.get(i));

            tab.setIcon(servicesImage.get(i));
            tab.setTabListener(this);
            actionBar.addTab(tab);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        //Code Comes here...
        System.out.println("Key Event:"+event.getAction()+",keyCode"+keyCode);
        onBackPressed();
        return true;
    }

    private List<Fragment> getFragments()
    {
        List<Fragment> fList = new ArrayList<Fragment>();

        if(menuInfo.contains("1"))
        {
            fList.add(TopUpFragment.newInstance(this,"Topup"));
        }
        if(menuInfo.contains("2"))
        {
            fList.add(BillPayFragment.newInstance(this,"Billpay"));
        }
        if(menuInfo.contains("4"))
        {
            fList.add(VoucherFragment.newInstance(this,"Voucher Sell"));
        }

        fList.add(MyAccountFragment.newInstance(this,"My Account"));
        fList.add(ReportFragment.newInstance(this,"Reports"));
        fList.add(SettingsListFragment.newInstance(this,"Settings"));

        return fList;
    }

    @Override
    public void onBackPressed() 
    {
        new AlertDialog.Builder(ButtonPayActivity.this)
        .setTitle( "Exit Application" )
        .setMessage( "Are you sure you want to Exit" )
        .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface arg0, int arg1) 
            {
                //do stuff onclick of YES
                finish();
            } 
        })
        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface arg0, int arg1)
            {
                //do stuff onclick of CANCEL
                arg0.dismiss();
            }

        }).show();
    }
    public static View prepareTabView(Context context, String text,int resId) {
        View view = LayoutInflater.from(context).inflate(
                R.layout.custom_tabview, null);
        ImageView iv = (ImageView) view.findViewById(R.id.iv_tabimage);
        iv.setImageResource(resId);
        TextView tv = (TextView) view.findViewById(R.id.tabIndicatorTextView);
        tv.setText(text);

        return view;
    }

    private class ActionBarTabMenuAdapter extends FragmentPagerAdapter  {
        Activity context;
        Context ctx;
        ArrayList<String> menuInfo;
        private List<Fragment> fragments;
        ArrayList<String> services;
        ArrayList<Integer> images;

        public ActionBarTabMenuAdapter(FragmentManager fm, List<Fragment> fragments,Context ctx,ArrayList<String> servicesName,ArrayList<Integer> servicesImage)
        {
            super(fm);
            this.context=(Activity) ctx;
            dataHelper=new DataHelper(ctx);
            menuInfo=dataHelper.getTransMenuInfo();
            dataHelper.close();

            this.services = servicesName;
            this.images = servicesImage;
            this.fragments = fragments;
            menuInfo.add("My Account");
            menuInfo.add("Reports");
            menuInfo.add("Settings");
            System.out.println("## Ctx in ButtonPay==>"+this.context);
        }

        @Override
        public int getCount() 
        {
            return menuInfo.size();
        }
        @Override
        public Fragment getItem(int position) {

            System.out.println("position of fragment--"+position);
            return this.fragments.get(position);
        }
    }

    class ViewHolder {
        TextView Title, Description, ReadMore;

    }

    public void onClick(View v) {

    }

    @Override
    public void onTabReselected(Tab tabposition, FragmentTransaction fragmentposition) {
        System.out.println("Tab Reselected method");

    }

    @Override
    public void onTabSelected(Tab tabposition, FragmentTransaction fragmentposition) {
        awesomePager.setCurrentItem(tabposition.getPosition());


    }

    @Override
    public void onTabUnselected(Tab tabposition, FragmentTransaction fragmentposition) {
        System.out.println("Tab unselected method");
        System.out.println("tab posiiton in unselected method---"+tabposition.getPosition());
        System.out.println("fragment position in unselected method---"+tabposition);
    }

    public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
        getSupportMenuInflater().inflate(R.menu.menu, menu);

        MenuItem searchItem = menu.findItem(R.id.menu_item_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setQueryHint("Search for Products");
        searchView.setOnQueryTextListener(this);
        searchView.setOnSuggestionListener(this);

        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        Toast.makeText(this, "You searched for: " + query, Toast.LENGTH_LONG).show();
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }

    @Override
    public boolean onSuggestionSelect(int position) {
        return false;
    }

    @Override
    public boolean onSuggestionClick(int position) {
        Toast.makeText(this, "Suggestion clicked: ",Toast.LENGTH_LONG).show();
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
        case R.id.menu_Home:
            startActivityForResult(new Intent(ButtonPayActivity.this,ButtonPayActivity.class), 11);
            break;      
        case R.id.menu_favourite:
            finish();
            startActivityForResult(new Intent(ButtonPayActivity.this,FavouriteMenuActivity.class), 11);
            break;
        case R.id.menu_Balance:
            new Thread(new GetBalanceInfoRunnable(mContext)).start();

            break;
        case R.id.menu_logout:
            new AlertDialog.Builder(ButtonPayActivity.this)
            .setTitle( "Exit Application")
            .setMessage( "Are you sure you want to Logout?")
            .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface arg0, int arg1) 
                {
                    //do stuff onclick of YES
                    setResult(2);
                    finish();
                }
            })
            .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface arg0, int arg1)
                {
                    //do stuff onclick of CANCEL
                    arg0.dismiss();
                }
            }).show();
            break;
        }
        return super.onOptionsItemSelected(item);
    }
}

Фрагмент ::

public class TopUpFragment extends SherlockFragment 
{
    public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    LinkedHashMap<String,String>listHeader;
    ArrayList<String> topupProSectionID;
    ArrayList<String> topupProSectionsName;
    ArrayList<TopupProSectionName.Products> listDataChild;
    static Context ctx;
    static TopUpFragment f ;
    private DataHelper dataHelper;
    private int lastExpandedPosition = -1;
    private ArrayList<TopupProSectionName> mTopupGroupCollection;
    public static TopUpFragment newInstance(Activity context,String string)
    {
        f = new TopUpFragment();
        ctx=context;
        System.out.println("$$$ onNewInst==>"+ctx);
        return f;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
        //String message = getArguments().getString(EXTRA_MESSAGE);
        View v = inflater.inflate(R.layout.myfragment_layout, container, false);
        //TextView messageTextView = (TextView)v.findViewById(R.id.textView);
        //messageTextView.setText(message);
        expListView = (ExpandableListView)v.findViewById(R.id.lvExp);
        prepareListData();
        System.out.println("%%% Ctx==>"+ctx);
        return v;
    }



    private void prepareListData()
    {
        listHeader = new LinkedHashMap<String, String>();
        dataHelper=new DataHelper(ctx);
        topupProSectionID=new ArrayList<String>();
        listHeader = dataHelper.getSectionSForTopupProduct();

        if (listHeader != null) 
        {
            Map.Entry me = null;
            Set entrySet = listHeader.entrySet();
            Iterator i = entrySet.iterator();
            mTopupGroupCollection = new ArrayList<TopupProSectionName>();
            TopupProSectionName sectionName = null;
            TopupProSectionName.Products topupProduct = null;

            while (i.hasNext()) 
            {
                sectionName = new TopupProSectionName();
                me = (Map.Entry)i.next(); 
                System.out.print("-->"+me.getKey() + ": "); 
                System.out.println(me.getValue()); 

                sectionName.setsectionName((String)me.getKey());

                listDataChild=new ArrayList<TopupProSectionName.Products>();
                listDataChild=dataHelper.getFlexiProducts(me.getValue().toString());
                listDataChild=dataHelper.getFixProducts(me.getValue().toString(),listDataChild);

                System.out.println("Getting products for sys ser ID:"+me.getValue().toString());
                //billpayProSectionsName.add((String) me.getKey());
                topupProSectionID.add((String) me.getValue());

                for(int index=0;index<listDataChild.size();index++)
                {
                    topupProduct = sectionName.new Products();
                    if(listDataChild.get(index).getSystemServiceID().equals(me.getValue()))
                    {
                        topupProduct.setProductName(listDataChild.get(index).getProductName());
                        topupProduct.setProductID(listDataChild.get(index).getProductID());
                        sectionName.topupProductList.add(topupProduct);
                    }
                }
                mTopupGroupCollection.add(sectionName);
            }
        }
        dataHelper.close();
        listAdapter = new ExpandableListAdapter(ctx,mTopupGroupCollection,expListView);
        expListView.setAdapter(listAdapter);
    }

    class ExpandableListAdapter extends BaseExpandableListAdapter {

        private Context _context;
        private ArrayList<TopupProSectionName> listDataHeader; // header titles
        ArrayList<TopupProSectionName.Products> topupProducts;
        private int[] groupStatus;
        private ExpandableListView mExpandableListView;

        public ExpandableListAdapter(Context context,
                ArrayList<TopupProSectionName>sectionName,ExpandableListView pExpandableListView)
        {
            this._context = context;
            this.listDataHeader = sectionName;
            this.topupProducts = listDataChild;
            mExpandableListView = pExpandableListView;
            groupStatus = new int[listDataHeader.size()];


            setListEvent();
        }

        private void setListEvent() 
        {
            mExpandableListView.setOnGroupExpandListener(new OnGroupExpandListener() 
            {
                public void onGroupExpand(int groupPosition) 
                {
                    //collapse the old expanded group, if not the same as new group to expand
                    //groupStatus[position] = 1;

                    if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition) 
                    {
                        mExpandableListView.collapseGroup(lastExpandedPosition);
                    }
                    lastExpandedPosition = groupPosition;
                }
            });

            /*mExpandableListView.setOnGroupCollapseListener(new OnGroupCollapseListener() 
           {
            @Override
            public void onGroupCollapse(int position) 
            {
             groupStatus[position] = 0;
            }
           });*/

            mExpandableListView.setOnChildClickListener(new OnChildClickListener() 
            {
                @Override
                public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id) 
                {
                    String ID=listDataHeader.get(groupPosition).topupProductList.get(childPosition).getProductID();
                    System.out.println("Product ID in Adapter==>"+ID);
                    return true;
                }
            });
        }

        @Override
        public String getChild(int groupPosition, int childPosititon) {
            return listDataHeader.get(groupPosition).topupProductList.get(childPosititon).getProductName();
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, final int childPosition,
                boolean isLastChild, View convertView, ViewGroup parent) {
            ChildHolder childHolder;

            if (convertView == null)
            {
                LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_item_fragment, null);

                childHolder = new ChildHolder();


                childHolder.title = (TextView) convertView.findViewById(R.id.lblListItem);

                convertView.setTag(childHolder);
            }
            else 
            {
                childHolder = (ChildHolder) convertView.getTag();
            }

            childHolder.title.setText(mTopupGroupCollection.get(groupPosition).topupProductList.get(childPosition).getProductName());
            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return mTopupGroupCollection.get(groupPosition).topupProductList.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return mTopupGroupCollection.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return mTopupGroupCollection.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) 
        {
            GroupHolder groupHolder;
            if (convertView == null) 
            {
                LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_group, null);
                groupHolder = new GroupHolder();

                groupHolder.title = (TextView) convertView.findViewById(R.id.lblListHeader);


                convertView.setTag(groupHolder);
            }
            else 
            {
                groupHolder = (GroupHolder) convertView.getTag();
            }
            groupHolder.title.setTypeface(null, Typeface.BOLD);
            groupHolder.title.setText(mTopupGroupCollection.get(groupPosition).getsectionName());

            return convertView;
        }


        class GroupHolder {
            TextView title;
        }

        class ChildHolder {
            TextView title;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
}

person AndroidLearner    schedule 05.12.2013    source источник


Ответы (1)


Я на самом деле неправильно получаю панель действий.

Чтобы использовать панель действий в каждом фрагменте::

я поместил setHasOptionsMenu(true); в свой onCreate() фрагмент

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

После этого я могу использовать onCreateOptionMenu(), в котором я поместил представление поиска, и теперь я могу искать дату из расширяемого списка, получая текст из представления поиска.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) 
{
    super.onCreateOptionsMenu(menu, inflater);

    inflater.inflate(R.menu.menu, menu);
    final MenuItem searchItem = menu.findItem(R.id.menu_item_search);
    final SearchView searchView = (SearchView) searchItem.getActionView();
    searchView.setQueryHint("Search Here");
}

И вот, готово, проблема решена.... ;)

person AndroidLearner    schedule 06.12.2013