简体   繁体   中英

Typecast context into Activity for use in Recycle View? (Kotlin)

I can send data from activity to recyclerview adapter file without any problems.

Typecast context into Activity

For example, I can type

var x:Int = 9000

in MainActivity file and then I go to RecyclerAdapter and simply type

var y:Int = MainActivity().x

to have RecyclerAdapter fetch it and use it to preform its operations.

I can't actually do the same, transferring data from RecyclerAdapter() to MainActivity(). I tried

var x:Int= 9000

in RecyclerAdapter() and then

var y:Int= RecyclerAdapter().x

inside MainActivity but the app doesn't fetch the data.

What should I do? I already tried googling for solutions but most were solutions to complex code. My actual app is also pretty complex but I would like to have a sample solution to this simple problem then work my way up from there onward.

Edit: Sorry I got the naming of the variables wrong. I corrected it now.

You can do it like this....

 val activity = context as ExampleActivity
 var i=activity.getCount()

In your Activity Class.

class ExampleActivity: AppCompatActivity() {


    private var count = 0

     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_example)
        var mList = findViewById(R.id.list) as RecyclerView
        var mAdapter = CustomAdapter(this);
        mList.layoutManager = LinearLayoutManager(this)
        mList.adapter = mAdapter
      }

    fun setCount(i: Int) {
        count = i
    }

    fun getCount(): Int {
        return count
    }
}

In Your AdapterClass.

class CustomAdapter(var context:Context) : RecyclerView.Adapter<CustomHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomHolder {
        return CustomHolder(LayoutInflater.from(context).inflate(R.layout.cell,parent,false))
    }

    override fun getItemCount(): Int {
        return 10;
    }

    override fun onBindViewHolder(holder: CustomHolder, position: Int) {

        val activity = context as ExampleActivity
        var i=activity.getCount()
         i+=20
        activity.setCount(i)
    }


}

class CustomHolder(val item: View) : RecyclerView.ViewHolder(item) {

}

This will provide you Abstraction Functionality of Classes .

Hope you understand by this.....

Nevermind. I got a workaround. Posting here for anyone who wants an answer for reference.

Create an Object kotlin file, then pass data from recycler adapter file to Object, then from Object to MainActivity

Example: In recycler adapter file: Object.x = x

Then in MainActivity(): x = Object.x

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