简体   繁体   中英

How to pass variable from Activity to Adapter

I need to pass a variable from an Activity to a GridView Adapter. What I tried was:

Declaring a method inside the activity:

public int getPoints()
{
    return points;
}

The in the adapter I declared:

mainActivity sel= new mainActivity();

And finally I called the method using:

int myPoints = sel.getPoints();

But it always returns 0. What is wrong with the code?

  1. Add argument to your adapter constructor
  2. Pass your variable when instantiating adapter MyGridAdapter adapter = new MyGridAdapter(myVariable)

To update variable from your activity you can also create method in your adapter and call it adapter.updateMyVariable(newVariable);

在mainActivity中创建公共静态变量点,然后从适配器mainActivity.points中调用。

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