gpt4 book ai didi

java - CustomAdapter 中的 onClick 监听器和上下文存在问题

转载 作者:行者123 更新时间:2023-12-02 12:14:26 24 4
gpt4 key购买 nike

我正在尝试构建一个 ArrayAdapter,允许用户访问链接到互联网、谷歌地图等的各个 TextView 字段。我无法解决错误状态为

Cannot resolve method 'startActivity (android.content.Intent).

浏览了这里的很多帖子后,我确定这是 context 的问题,我不确定如何从下面的代码中得到这个问题。任何帮助将不胜感激:)

package com.example.stuart.listitemviewtest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;


public class AttractionAdapter extends ArrayAdapter {
public AttractionAdapter(Context context, ArrayList<Attraction> attractions) {
super(context, 0, attractions);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
// Get the {@link currentAttraction} object located at this position in the list
final Attraction currentAttraction = (Attraction) getItem(position);

final TextView attractionName = (TextView) listItemView.findViewById(R.id.attraction_name);
attractionName.setText(currentAttraction.getmName());
attractionName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("attraction Name", "the name of attraction: " + currentAttraction.getmName());
}
});
TextView attractionURL =(TextView) listItemView.findViewById(R.id.attraction_URL);
attractionURL.setText(currentAttraction.getmWebAddress());
attractionURL.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

//get web address
Log.i("Web Address", "The web address is: " + currentAttraction.getmWebAddress());


//load URL in new window
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse(currentAttraction.getmWebAddress()));
startActivity(intent);
}
});
return listItemView;
}
}

最佳答案

像这样更改你的构造函数:-

  Context mContext;
public AttractionAdapter(Context context, ArrayList<Attraction> attractions) {
super(context, 0, attractions);
mContext = context;
}

现在在startActivity()之前使用mContext;

   Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse(currentAttraction.getmWebAddress()));
mContext.startActivity(intent);

关于java - CustomAdapter 中的 onClick 监听器和上下文存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46301130/

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