使用CAB在ListView中进行多项选择

时间:2013-11-10 20:14:05

标签: android listview header actionbarsherlock android-actionmode

我正在为片段中的列表设置上下文操作栏。 使用 ActionBarSherlock 在前HONEYCOMB版本的android中使用多选获取 CAB

我正在流动此tutorial,但在执行长按后应用程序崩溃

这是我的代码

public class CreateFragment extends SherlockFragment {
    private ArrayList<Game> myGames;
    public ArrayAdapter<String> adapter;
    private TipspromenadApplication app;
    private ListView listView;
    private ActionMode mActionMode;

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

        listView = (ListView) view.findViewById(R.id.createdGames);
        View header = getActivity().getLayoutInflater().inflate(R.layout.list_header_create_fragment, null);
        listView.addHeaderView(header);

        final ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < myGames.size(); i++) {
            list.add(myGames.get(i).getLocation() + " " + new SimpleDateFormat("dd/MM/yy", Locale.getDefault()).format(myGames.get(i).getEventDate()));
        }
//      adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_multiple_choice, list);
//      listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
                Intent intent= new Intent(getActivity(), CreateTabActivity.class);
                intent.putExtra("GameID", position-1);
                startActivity(intent);  
            }
        });

        listView.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
                onListItemCheck(position);
                return true;
            }
        });

        listView.setAdapter(new SelectableAdapter(this, list));


        return view; 
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = (TipspromenadApplication) getActivity().getApplication();     
        this.myGames = app.loadGames();
    }

    //@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {    
        if(mActionMode == null) {
            // no items selected, so perform item click actions
        } else
            // add or remove selection for current list item
            onListItemCheck(position);     
    }  

    private void onListItemCheck(int position) {
    SelectableAdapter adapter = (SelectableAdapter) listView.getAdapter();
    adapter.toggleSelection(position);
    boolean hasCheckedItems = adapter.getSelectedCount() > 0;       

    if (hasCheckedItems && mActionMode == null)
        // there are some selected items, start the actionMode
        mActionMode = getSherlockActivity().startActionMode(new ActionModeCallback());
    else if (!hasCheckedItems && mActionMode != null)
        // there no selected items, finish the actionMode
        mActionMode.finish();


    if(mActionMode != null)
        mActionMode.setTitle(String.valueOf(adapter.getSelectedCount()) + " selected");
    }

    private class SelectableAdapter extends ArrayAdapter<String>{

        private SparseBooleanArray mSelectedItemsIds;

        public SelectableAdapter(CreateFragment createFragment, ArrayList<String> list) {
            super(getActivity(), android.R.layout.simple_list_item_1, list);
            mSelectedItemsIds = new SparseBooleanArray();
        }

        public void toggleSelection(int position)
        {
            selectView(position, !mSelectedItemsIds.get(position));
        }

        public void removeSelection() {
            mSelectedItemsIds = new SparseBooleanArray();
            notifyDataSetChanged();
        }

        public void selectView(int position, boolean value)
        {
            if(value)
                mSelectedItemsIds.put(position, value);
            else
                mSelectedItemsIds.delete(position);

            notifyDataSetChanged();
        }

        public int getSelectedCount() {
            return mSelectedItemsIds.size();// mSelectedCount;
        }

        public SparseBooleanArray getSelectedIds() {
            return mSelectedItemsIds;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if(convertView == null){
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(android.R.layout.simple_list_item_1, null);
            }           
            ((TextView) convertView).setText(getItem(position));    
            //change background color if list item is selected
            convertView.setBackgroundColor(mSelectedItemsIds.get(position)? 0x9934B5E4: Color.TRANSPARENT);         

            return convertView;
        }

    }

    private class ActionModeCallback implements ActionMode.Callback {

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // inflate contextual menu  
            mode.getMenuInflater().inflate(R.menu.create, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {            
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // Respond to clicks on the actions in the CAB
            switch (item.getItemId()) {
                case R.id.share:
                    // do s.th.
                    mode.finish(); // Action picked, so close the CAB
                    return true;
                case R.id.delete:
                    // do s.th.
                    mode.finish(); // Action picked, so close the CAB
                    return true;
                default:
                    return false;
        }
    }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            // remove selection 
            SelectableAdapter adapter = (SelectableAdapter) listView.getAdapter();
            adapter.removeSelection();
            mActionMode = null;
        }   
    }
}

这是 LogCat 中的错误:

FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.HeaderViewListAdapter cannot be cast to com.damson.android.tipspromenad.tabs.CreateFragment$SelectableAdapter
at com.damson.android.tipspromenad.tabs.CreateFragment.onListItemCheck(CreateFragment.java:113)
at com.damson.android.tipspromenad.tabs.CreateFragment.access$2(CreateFragment.java:112)
at com.damson.android.tipspromenad.tabs.CreateFragment$2.onItemLongClick(CreateFragment.java:66)
at android.widget.AbsListView.performLongPress(AbsListView.java:2925)
at android.widget.AbsListView$CheckForLongPress.run(AbsListView.java:2875)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:4787)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
at dalvik.system.NativeStart.main(Native Method)

很抱歉很长的问题!我希望你能帮助我:)谢谢!

1 个答案:

答案 0 :(得分:1)

该教程不使用addHeaderView()。您的代码使用addHeaderView()。您的错误涉及标题视图:

java.lang.ClassCastException: android.widget.HeaderViewListAdapter cannot be cast to com.damson.android.tipspromenad.tabs.CreateFragment$SelectableAdapter

这是因为当你致电addHeaderView()时,getListAdapter()将不再返回你自己的适配器,而是一个新的适配器,一个包装你的适配器并提供标题视图。

致电getWrappedAdapter() on the HeaderViewListAdapter以获取SelectableAdapter


<强>更新

HeaderViewListAdapter wasThisReallySoHard=(HeaderViewListAdapter)listView.getAdapter();
SelectableAdapter adapter=(SelectableAdapter)wasThisReallySoHard.getWrappedAdapter();