构造函数中传递的上下文显示错误



我是android开发的初学者。我试图制作自定义数组适配器来显示一些东西。但当我传递主活动的参数时,它显示上下文中有错误如所需类型上下文和提供的主要活动。。

这是我的第一个问题,朋友们,请帮我解决
主要活动。java

package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<text> arr= new ArrayList<>();
arr.add(new text(4,5));
textadapter extadapter=new textadapter(this,arr);
ListView listView=findViewById(R.id.list_item);
listView.setAdapter(extadapter);
}
}

自定义阵列适配器

public class textadapter extends ArrayAdapter {

public textadapter(@NonNull Context context,ArrayList<text> arrayList) {
super(context,0,arrayList);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if(convertView==null){
convertView= LayoutInflater.from(getContext()).inflate(R.layout.list,parent,false);
}
text a= (text) getItem(position);
TextView t=convertView.findViewById(R.id.text);
TextView T1=convertView.findViewById(R.id.text2);
t.setText(a.getText());
T1.setText(a.getStext());
return convertView;
}
}

将TextAdapter类中getView((方法中的getContext((更改为context,并生成一个名为mContext的变量,因为您已经将Main Activity context传递到Adapter Constructor中。

public class textadapter extends ArrayAdapter {
private Context context;
public textadapter(@NonNull Context context,ArrayList<text> arrayList) {
super(context,arrayList);
this.context = context;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if(convertView==null){
convertView= LayoutInflater.from(context).inflate(R.layout.list,parent,false);
}
text a= (text) getItem(position);
TextView t=convertView.findViewById(R.id.text);
TextView T1=convertView.findViewById(R.id.text2);
t.setText(a.getText());
T1.setText(a.getStext());
return convertView;
}

最新更新