Kotiln:将数据从适配器传递到活动

时间:2019-06-30 16:17:31

标签: android android-intent android-activity kotlin android-recyclerview

我尝试使用adapter将数据从activity传递到其他putExtra,但是当我单击列表中的项目以移至第二个{{1} },则不会检索任何数据,并且不会显示我输入的默认文本。 另一种方法呢?或我想念什么? 这是我的代码:

  

我的activity

onBindViewHolder
  

我的第二个override fun onBindViewHolder(holder: AlbumsListViewHolder, position: Int) { val AlbumsData = albumsData!![position] holder.albumsName.text = AlbumsData.title Glide.with(holder.itemView) .load(AlbumsData.cover) .transition(DrawableTransitionOptions.withCrossFade()) .into(holder.coverImage) holder.itemView.setOnClickListener { val intent = Intent(holder.itemView.context, TracksActivity::class.java) //listener?.onClick(AlbumsData) intent.putExtra("dd", "ff") holder.itemView.context.startActivity(intent) } }

Activity

1 个答案:

答案 0 :(得分:1)

您可以使用callback 首先,在适配器中定义一个回调,如下所示:

    interface CallbackInterface {   
        fun passDataCallback(message: String)
    }

然后在您的interface中初始化回调adapter

class YourAdapter(private val callbackInterface:CallbackInterface) :
    RecyclerView.Adapter<CurrencyListAdapter.ViewHolder>() {
.
.
.
}

然后从onBindViewHolder()内部的接口使用回调方法,如下所示:

holder.itemView.setOnClickListener {
        //Set your codes about intent here
        callbackInterface.passResultCallback("Your message")
}

最后,像这样在callback中实现activity方法:

class TracksActivity: AppCompatActivity(), TracksView , YourAdapterName.CallbackInterface {

    private var albumsAdapter: AlbumsAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        setContentView(R.layout.activity_tracks)
    }

  override fun passResultCallback(message: String) {
         //message is "ff"
    }
}

更新:

如果您不使用callback,则只需将activity更改为:

class TracksActivity: AppCompatActivity(), TracksView {

    private var albumsAdapter: AlbumsAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        setContentView(R.layout.activity_tracks)

        var bundle : Bundle? = intent.extras
        var message = bundle!!.getString("dd") 
        Log.d("dd", "${message}")
    }
}