当时我是直接单独建了一个.java文件ListViewActivity.java来填充adapter,但是运行之后list view不显示,空空如也,怎么也解决不来。后来我把listview写在了mainactivity中就成功了,如果有大佬知道为什么请不吝赐教,下面的代码先是无法实现的,之后是可以实现的,如果有小伙伴有这样的情况出现,可以尝试一下我的方法
无法显示listview的内容的代码如下:
ListViewActivity.java
import android.support.annotation.Nullable;
import android.widget.ListView;
public class ListViewActivity extends Activity {
private ListView mlv1;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page_01);
mlv1 = findViewById(R.id.lv_1);
MyListAdapter adapter = new MyListAdapter(this);
mlv1.setAdapter(adapter);
}
}
MyListAdapter.java
package com.example.a17919.demo1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends BaseAdapter {
public Context mContent;
private LayoutInflater mlayoutflater;
public MyListAdapter(Context context)
{
this.mContent = context;
mlayoutflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return 5;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
class ViewHolder{
public ImageView imageView;
public TextView tvTitle,tvTime,tvContent;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null)
{
holder = new ViewHolder();
convertView = mlayoutflater.inflate(R.layout.layout_list_item,parent,false);
holder.imageView = convertView.findViewById(R.id.iv);
holder.tvTitle = convertView.findViewById(R.id.tv_title);
holder.tvTime = convertView.findViewById(R.id.tv_time);
holder.tvContent = convertView.findViewById(R.id.tv_content);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//给控件赋值
holder.imageView.setImageResource(R.drawable.ic_launcher_background);
holder.tvTitle.setText("这是标题");
holder.tvTime.setText("2020-12-12");
holder.tvContent.setText("这是内容");
return convertView;
}
}
layout_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
andro