简体   繁体   English

目的问​​题:如何使用另一个“适配器”类中的MainActivity将数据传递给SecondActivity

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

This is in Adapter.Java 这在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.. 我现在已经知道不在MainActivity类中时如何使用MainActivity.this。

Try following code. 尝试以下代码。

Solution 1 解决方案1

You have to pass context while you initialized Adapter in MainActivity . MainActivity初始化Adapter时必须传递context

In MainActivity.this : MainActivity.this

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

In your Adapter : 在您的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 解决方案2

Another option is interface 另一个选择是interface

Create one interface like below: 创建一个如下所示的interface

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 : 在您的Activity

AdapterInterface buttonListener;
public MainActivity extends AppCompactActivity implements AdapterInterface{

in onCreate 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 . 您可以在Adapter类中具有Activity类型的成员变量(例如, private Activity mActivity; ),并将MainActivity实例传递给Adapter类的构造函数中的Adapter类,然后将其分配给mActivity Some thing like this: 像这样的东西:

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

Then in your onClick method: 然后在您的onClick方法中:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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