简体   繁体   中英

Intent problem: how to use MainActivity from another class “Adapter” to pass data to SecondActivity

This is in Adapter.Java

    public void onClick(View v) {
        String name=listItemData.get(i).getName();
        Intent intent = Intent(MainActivity.this, SecondActivity.class);
        intent.putExtra("NAME", name);
    }

I have now idea how to use MainActivity.this when I'm not in MainActivity class..

Try following code.

Solution 1

You have to pass context while you initialized Adapter in MainActivity .

In MainActivity.this :

XyzAdapter adapter = new XyzAdapter(MainActivity.this, .. ..)

In your Adapter :

private Context mContext;
   public XyzAdapter(Context context .. ..){
      mContext = context;
   }

And then you can do like below:

public void onClick(View v) {
        String name=listItemData.get(i).getName();
        Intent intent = Intent(mContext, SecondActivity.class);
        intent.putExtra("NAME", name);
        mContext.startActivity(intent);
    }

Solution 2

Another option is interface

Create one interface like below:

public interface AdapterInterface {
        public void buttonPressed();
    }

Now in your adapter:

AdapterInterface buttonListener;
public XyzAdapter(Context context, AdapterInterface buttonListener)
{
  super(context,c,flags);
  this.buttonListener = buttonListener;
}

public void onClick(View v) {
      buttonListener.buttonPressed()
}

In your Activity :

AdapterInterface buttonListener;
public MainActivity extends AppCompactActivity implements AdapterInterface{

in onCreate

buttonListener = this;

XyzAdapter adapter = new XyzAdapter(MainActivity.this, buttonListener  .. ..)



@Override
public void buttonPressed(){
  // here you have to do once your click perform
}

You can have a member variable of type Activity in your Adapter class (eg private Activity mActivity; ) and pass your MainActivity instance to your Adapter class in the constructor of your Adapter class and assign it to mActivity . Some thing like this:

public Adapter(Activity activity) {
    this.mActivity = activity;
}

Then in your onClick method:

public void onClick(View v) {
    String name=listItemData.get(i).getName();
    Intent intent = new Intent(mActivity, SecondActivity.class);
    intent.putExtra("NAME", name);
    mActivity.startActivity(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