gpt4 book ai didi

java - Intent 问题: how to use MainActivity from another class "Adapter" to pass data to SecondActivity

转载 作者:行者123 更新时间:2023-12-02 10:07:57 25 4
gpt4 key购买 nike

这是在 Adapter.Java 中

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

我现在知道当我不在 MainActivity 类中时如何使用 MainActivity.this ..

最佳答案

尝试以下代码。

解决方案1

MainActivity 中初始化 Adapter 时,您必须传递 context

MainActivity.this中:

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

在您的适配器中:

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

然后你可以像下面这样做:

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

解决方案2

另一个选项是界面

创建一个界面,如下所示:

public interface AdapterInterface {
public void buttonPressed();
}

现在在您的适配器中:

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

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

在您的 Activity 中:

AdapterInterface buttonListener;
public MainActivity extends AppCompactActivity implements AdapterInterface{

onCreate

buttonListener = this;

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



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

关于java - Intent 问题: how to use MainActivity from another class "Adapter" to pass data to SecondActivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55203291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com