【发布时间】:2023-03-22 08:30:01
【问题描述】:
当列表中没有项目时,不会出现空视图。有什么问题?
Main_Activity
包 com.example.android.customadapter;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Players> objects = new ArrayList<>();
objects.add(new Players("Shikhar Dhawan",R.drawable.shikhar));
objects.add(new Players("Virat Kohli",R.drawable.kohli));
}
}
我的模型课
Players.java
包 com.example.android.customadapter;
public class Players {
private String mName;
private int image;
Players(String name,int res)
{
mName = name;
image = res;
}
public String getName()
{
return mName;
}
public int getImage()
{
return image;
}
}
CustomAdapter 类
包 com.example.android.customadapter;
我的自定义数组列表适配器
public class CustomAdapter extends ArrayAdapter<Players> {
public CustomAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<Players> objects) {
super(context, resource, objects);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View v = convertView;
if(v==null)
{
v = LayoutInflater.from(getContext()).inflate(R.layout.list_item,parent,false);
}
Players p = getItem(position);
TextView t = (TextView)v.findViewById(R.id.miwok_text_view);
t.setText(p.getName());
ImageView i = (ImageView)v.findViewById(R.id.image);
i.setImageResource(p.getImage());
return v;
}
}
【问题讨论】:
-
您没有在 OnCreate 中初始化您的 Listview,也没有为其设置适配器
-
Olena Y 感谢您的回复,但我该怎么做
-
CustomAdapter customAdapter = new CustomAdapter(this, words); ListView lv = (ListView) findViewById(R.id.list); lv.setAdapter(customAdapter );
标签: android listview custom-adapter