如何获取从其适配器类扩展ListFragment的活动的上下文?

时间:2015-01-07 11:38:29

标签: android android-arrayadapter android-listfragment android-context

这是我想要调用startActionMode的适配器类。我在setActionMode方法中调用它但得到了这些错误:

  1. 无法从Context转换为ActivityFragment。

  2. 方法startActionMode(ActivityFragment.ActionModeCallback)未定义类型 ActivityFragment。

  3. public class ListAdapter extends ArrayAdapter<ListGettersSetters>
    {
        ArrayList<ListGettersSetters> arrayListGettersSetters;
        LayoutInflater layoutInflater;
        Context context;
        int Resource, i = 0, j = 0, checkedItemsCount = 0;
        Animation animation1;
        Animation animation2;
        CheckBox flipCheckBox;
        viewHolder holder;
        ActionMode actionMode;
        boolean isActionModeShowing;
    
        static class viewHolder
        {
            public CheckBox imageView;
            public TextView textViewName;
            public TextView textViewData;
            public TextView textViewDetails;
        }   
    
        public ListAdapter(Context context, int resource, ArrayList<ListGettersSetters> arrayListGettersSetters) 
        {
            super(context, resource, arrayListGettersSetters);
            this.arrayListGettersSetters = arrayListGettersSetters;
            Resource = resource;
            this.context = context;
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
            animation1 = AnimationUtils.loadAnimation(context, R.anim.to_middle);
            animation2 = AnimationUtils.loadAnimation(context, R.anim.from_middle);
    
            isActionModeShowing = false;
        }
    
        @Override
        public int getCount() 
        {
            return arrayListGettersSetters.size();
        }
    
        @Override
        public ListGettersSettersgetItem(int position) 
        {
            return arrayListGettersSetters.get(position);
        }
    
        @Override
        public long getItemId(int position) 
        {
            return position;
        }
    
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) 
        {
            holder = new viewHolder();
            if(convertView == null)
            {
                convertView = layoutInflater.inflate(Resource, null);
    
                holder.imageView = (CheckBox) convertView.findViewById(R.id.id_for_checkBox);
                holder.textViewName = (TextView) convertView.findViewById(R.id.id_for_name_textView);
                holder.textViewData = (TextView) convertView.findViewById(R.id.id_for_data_textView);
                holder.textViewDetails = (TextView) convertView.findViewById(R.id.id_for_details_textView);
    
                convertView.setTag(holder);
            }
            else
            {
                holder = (viewHolder) convertView.getTag();
            }
    
            holder.textViewName.setText(getItem(position).getName());
            holder.textViewData.setText(getItem(position).getData());
            holder.textViewDetails.setText(getItem(position).getDetails());
            holder.imageView.setTag(position);
            holder.imageView.setOnClickListener(new OnClickListener() 
            {
                public void onClick(View view) 
                { 
                    flipCheckBox = (CheckBox) view;
                    flipCheckBox.clearAnimation();
                    flipCheckBox.setAnimation(animation1);
                    flipCheckBox.startAnimation(animation1);
                    setAnimListners(arrayListGettersSetters.get(Integer.parseInt(view.getTag().toString())));
                }
            });
    
            return convertView;
        }
    
        private void setAnimListners(final ListGettersSetters listGettersSetters)
        {
            AnimationListener animationListener = new AnimationListener()
            {
                @Override
                public void onAnimationStart(Animation animation) 
                {
                    if (animation == animation1) 
                    {
                        flipCheckBox.clearAnimation();
                        flipCheckBox.setAnimation(animation2);
                        flipCheckBox.startAnimation(animation2);
                    } 
                    else 
                    {
                        listGettersSetters.setIsChecked(!listGettersSetters.isChecked());
                        setCount();
                        setActionMode();
                    }
                }
    
                public void setCount() 
                {
                    if (listGettersSetters.isChecked()) 
                    {
                        checkedItemsCount++;
                    } 
                    else 
                    {
                        if (checkedItemsCount != 0) 
                        {
                            checkedItemsCount--;
                        }
                    }
    
                    Log.v("Checked items count", checkedItemsCount + "");
                }
    
                private void setActionMode() 
                {
                    if (checkedItemsCount > 0) 
                    {
                        if (!isActionModeShowing) 
                        {
                            actionMode = ((ActivityFragment) context).startActionMode(new ActivityFragment.ActionModeCallback(context));
                            isActionModeShowing = true;
                        }
                    } 
                    else if (actionMode != null) 
                    {
                        actionMode.finish();
                        isActionModeShowing = false;
                    }
    
                    if (actionMode != null)
                    {
                        actionMode.setTitle(String.valueOf(checkedItemsCount));
                    }
    
                    notifyDataSetChanged();
                }
    
                @Override
                public void onAnimationRepeat(Animation animation) 
                {
                }
    
                @Override
                public void onAnimationEnd(Animation animation) 
                {
                }
            };
            animation1.setAnimationListener(animationListener);
            animation2.setAnimationListener(animationListener);
        }
    

    这是我的ActivityFragment类,我在其中实现了一个名为ActionModeCallback的类,该类在我的适配器类中调用。此外,当我在这个内部类中获取ActivityFragment的上下文时,也会得到相同的错误。

    public class ActivityFragment extends ListFragment
    {
        @Override
        public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState)
        {
            View view = layoutInflater.inflate(R.layout.folders_fragment_listview, null, false);
    
            return view;
        }
    
        public static final class ActionModeCallback implements ActionMode.Callback
        {   
            Context context;
    
            public ActionModeCallback(Context context) 
            {
                this.context = context;
            }
    
            @Override
            public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) 
            {
                Toast toast = null;
                ArrayList<FoldersFragmentGettersSetters> selectedListItems = new ArrayList<FoldersFragmentGettersSetters>();
    
                StringBuilder selectedItems = new StringBuilder();
    
                for (FoldersFragmentGettersSetters foldersFragmentGettersSetters : ((ActivityFragment ) context).listAdapter.arrayListGettersSetters) 
                {
                    if (foldersFragmentGettersSetters.isChecked()) 
                    {
                        selectedListItems.add(foldersFragmentGettersSetters);
                    }
                }
    
                if (menuItem.getTitle().equals("Delete")) 
                {
                    toast = Toast.makeText(context, "Delete: " + selectedItems.toString(), Toast.LENGTH_SHORT);
                } 
                else if (menuItem.getTitle().equals("Archive")) 
                {
                    toast = Toast.makeText(context, "Archive: " + selectedItems.toString(), Toast.LENGTH_SHORT);
                } 
                else if (menuItem.getTitle().equals("Mark unread")) 
                {
                    toast = Toast.makeText(context, "Mark unread: " + selectedItems.toString(), Toast.LENGTH_SHORT);
                } 
                else if (menuItem.getTitle().equals("Move")) 
                {
                    toast = Toast.makeText(context, "Move: " + selectedItems.toString(), Toast.LENGTH_SHORT);
                } 
                else if (menuItem.getTitle().equals("Remove star")) 
                {
                    toast = Toast.makeText(context, "Remove star: " + selectedItems.toString(), Toast.LENGTH_SHORT);
                }
                if (toast != null) 
                {
                    toast.show();
                }
                actionMode.finish();
                return true;
            }
    
            @Override
            public boolean onCreateActionMode(ActionMode actionMode, Menu menu) 
            {
                menu.add("Delete").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
                menu.add("Archive").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
                menu.add("Mark unread").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
                menu.add("Move").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
                menu.add("Remove star").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    
                return true;
            }
    
            @Override
            public void onDestroyActionMode(ActionMode actionMode) 
            {
                ((ActivityFragment ) context).inboxAdapter.checkedItemsCount = 0;
                ((ActivityFragment ) context).inboxAdapter.isActionModeShowing = false;
                for (FoldersFragmentGettersSetters foldersFragmentGettersSettersItem : ((InboxFragment) context).inboxList) 
                {
                    foldersFragmentGettersSettersItem.setIsChecked(false);
                }
                ((ActivityFragment ) context).listAdapter.notifyDataSetChanged();
    
                Toast.makeText(context, "Action mode closed", Toast.LENGTH_SHORT).show();
            }
    
            @Override
            public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) 
            {       
                return false;
            }
        }
    }
    

2 个答案:

答案 0 :(得分:3)

修改ListAdapter的构造函数
public ListAdapter(Context context, int resource, ArrayList<ListGettersSetters> arrayListGettersSetters) 

public ListAdapter(ActivityFragment context, int resource, ArrayList<ListGettersSetters> arrayListGettersSetters)

答案 1 :(得分:2)

一种好的方法是使用回调。

  1. 在适配器类中创建回调接口(侦听器)。
  2. 声明接口的实例变量,例如startActionModeCallback
  3. 在适配器构造函数中,传递侦听器对象并将其分配给startActionModeCallback
  4. 当您在ActivityFragment中创建适配器实例时,将其作为侦听器传递并在片段中实现其回调方法。
  5. 在适配器的任何位置调用回调方法,它将被片段监听。
  6. 希望对你有意义。你可以问我澄清一下。祝你好运!


    示例

    适配器类

    public class ListAdapter extends ArrayAdapter<ListGettersSetters>
    {
    
    Interface StartActionInterface
    {
    public void startActionMode();
    }
    
    
    //declare other instance variables and add following
    
    StartActionInterface startActionModeListener;
    
    //change your constructor as:
    
    public ListAdapter(Context context, int resource, ArrayList<ListGettersSetters> arrayListGettersSetters, StartActionInterface listener) 
    {
    //normal code
    startActionModeListener = listener;
    }
    
    }
    

    <强> ActivityFragment

    public class ActivityFragment extends ListFragment implements StartActionInterface
    {
        @Override
        public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState)
        {
            View view = layoutInflater.inflate(R.layout.folders_fragment_listview, null, false);
    
    ////////initialize adapter and pass `this` in last argument
    
            return view;
        }
    
    //Implement callback method. Also implement `setActionMode()` method here in fragment. 
    
    void startActionMode()
    {
    setActionMode();
    }
    
    }
    

    在函数setActionMode()中,替换以下行:

     if (!isActionModeShowing) 
     {
        actionMode = ((ActivityFragment) context).startActionMode(new ActivityFragment.ActionModeCallback(context));
                            isActionModeShowing = true;
      }
    

    使用:

    if (!isActionModeShowing) 
    {
        actionMode = getActivity().startActionMode(new ActionModeCallback(getActivity()));
                            isActionModeShowing = true;
    }