我正在创建一个自定义的适配器MyAdapter并扩展一个ListView listView以显示String数据数组。使用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。
使用this
:
MyAdapter adapter = new MyAdapter(this, data);
关于android - 无法解析我用来初始化适配器的方法“getActivity()”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53227902/