gpt4 book ai didi

java - 无法解析我用来初始化适配器的方法 'getActivity()'

转载 作者:行者123 更新时间:2023-11-29 15:34:46 25 4
gpt4 key购买 nike

我正在创建自定义适配器 MyAdapter 并扩充 ListView listView 以显示字符串数组 data。使用 getActivity() 方法初始化 MyAdapter 时出现错误,如下所示:

public class MainActivity extends AppCompatActivity {

private ListView listView;
private String[] data = {"Sanskrit", "Bhojpuri", "Newari", "Magar",
"Gurung", "English", "Maithili", "Tamil", "Hindi",
"French", "German", "Russian", "Chinese"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView = findViewById(R.id.list_view);

MyAdapter adapter = new MyAdapter(getActivity(), data);
listView.setAdapter(adapter);
}
}

class MyAdapter extends ArrayAdapter {
String[] data;

public MyAdapter(Context context, int res, String[] data) {
super(context,res);

this.data = data;
}

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {

LayoutInflater inflater = (LayoutInflater) getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View row = inflater.inflate(R.layout.custom_list_view, parent, false);

TextView textView = row.findViewById(R.id.textView);

textView.setText(data[position]);
return row;
}
}

如有任何帮助,我们将不胜感激。

最佳答案

当您初始化 MyAdapter 时,您已经在 Activity 中。 Activity 类没有 getActivity() 方法,因为它已经是 Activity。

使用这个:

MyAdapter adapter = new MyAdapter(this, data);

关于java - 无法解析我用来初始化适配器的方法 'getActivity()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53227902/

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