Android communication between fragment and baseadapter

后端 未结 2 993
别那么骄傲
别那么骄傲 2020-12-29 15:31

Need expert opinion how should i structure this issue. I have a custom method process_filter that resides in a fragment as it needs to access a private

2条回答
  •  囚心锁ツ
    2020-12-29 15:39

    Create an interface from your adapter to your fragment.

    In your adapter create the interface and pass it in your adapter's constructor

    class MyAdapter extends BaseAdapter {
    
        public interface IProcessFilter {
            void onProcessFilter(String string1, String string2)
        }
    
        private IProcessFilter mCallback;
    
        public MyAdapter(Context context, String string1, String string2, IProcessFilter callback) {
            mCallback = callback;
        }
    
        public View getView( final int position, View convertView, ViewGroup   parent)
        {
            holder.checkBox.setOnClickListener( new View.OnClickListener() {
                public void onClick(View v) {
                    mCallback.onProcessFilter("string1", "string2");
                }
            }
       }
    }
    

    Last thing, implement it in your fragment like this

    public class MyFragment extends Fragment implements IProcessFilter {
        ...
        ...
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            View view = inflater.inflate(R.layout.my_fragment_layout, container, false);
            no_of_filter = (TextView) view.findViewById(R.id.no_of_filter_tv);
    
            MyAdapter custom_adapter = new MyAdapter(context, "string 1", "string 2", this);  
        }
    
        @Override
        public void onProcessFilter(String string1, String string2) {
            // Process the filter
        }
    }
    

提交回复
热议问题