简体   繁体   中英

How to startActivityForResult in RecyclerView adapter and override onActivityResult?

The startActivity in recyclerView adapter works fine but when I try to startActivityForResult in recyclerView adapter and I override the onActivityResult (in mainActivity) not works properly.

in kotlin you can try pass a function as a param to your adapter like this inside you class Adapter:

class MyAdapter(val context: Context, 
                val list: List<Any?>,
                val onClickFunction: ((Any?) -> Unit)? = null) {
    // previous class's properties and functions ..

    fun override onBindViewHolder(holder: MyHolder, position: Int) {
        // previous code ..
        holder.whatEverYouWantClick.setOnClickListener {
           this@MyAdapter.onClickFunction?.invoke(list.get(position));
        }
    }
}

and in your "setRecyclerView" function you put this:

mRecyclerView.adapter = MyAdapter(context, listOfWhatEverIWant) {
    // the on click will run here

    // storage the results ..

    this.finish()
}

If you don't understand what I'm doing, I'm passing a function to the adapter runs on one specific position element is clicked, this function set the results and finish to return back the result for the caller activity.

You are doing it wrong it's not for your adapter to handle what to do on click. I would suggest that you, that you create a interface to create a listener:

public interface AdapterItemClickListener<T>
{
    void onItemClicked(final T item);
}

Then in your adapter constructor you have something like this:

private final AdapterItemClickListener<Object> _listener;
ListAdapter(final AdapterItemClickListener<Object> listener)
{
    _listener = listener;
}

so when you bind (I have no code so i'm supposing you're using a RecyclerView.Adapter)

 @Override
    public void onBindViewHolder(final ViewHolder holder, final int position)
    {
        holder.itemView.setOnClickListener(v -> _listener.onItemClicked(getItem(position)));
    }

your activity will need to implement the interface then inactivity you will have to create your adapter like this:

_adapter = ListAdapter(this);

end add this method

  private void onItemClicked(final Object item)
    {
       startActivityForResult(Intent);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM