Android ListView在Fragment中的使用示例详解

  public class RegistFragment extends Fragment {

  private RegistViewModel viewModel;

  private FragmentRegistBinding binding;

  private ListView myListView;

  @Override

  public void onStart() {

  super.onStart();

  }

  @Override

  public void onCreate(@Nullable Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  viewModel = new ViewModelProvider(this).get(RegistViewModel.class);

  }

  @Nullable

  @Override

  public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

  if (binding == null) {

  binding = FragmentRegistBinding.inflate(inflater,container,false);

  binding.setViewModel(viewModel);//一定要在xml的中申明好才可以setViewModel

  binding.setLifecycleOwner(this);

  myListView = binding.lv;

  myListView.setAdapter(new myAdapter(viewModel.userList,getContext()));

  myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

  @Override

  public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

  Log.d("TAG", "onItemClick: "+i);

  }

  });

  }

  View rootView = binding.getRoot();

  return rootView;

  }

  /**

  * 给ListView设置适配器

  */

  public class myAdapter extends BaseAdapter{

  private List list;

  private Context context;//下面把数据显示到平台上会有用到这个参数

  public myAdapter(List list, Context context) {//创建构造方法

  this.list = list;

  this.context = context;

  }

  @Override

  public int getCount() {//listView能够显示多少数据,,一般是list有多少数据就会显示多少数据

  return list.size();

  }

  @Override

  public Object getItem(int i) {

  return null;

  }

  @Override

  public long getItemId(int i) {

  return i;

  }

  @Override

  public View getView(int i, View view, ViewGroup viewGroup) {//把数据显示到界面上

  //1.拿到布局文件,为了方式view不停创建我们需要做一个判断,当view为空的时候再去创建

  ViewHoder viewHoder;

  if (view == null) {

  //每次都要去找这个控件比较耗时,如何解决呢?我们需要创建一个viewHoder

  viewHoder = new ViewHoder();

  view = LayoutInflater.from(context).inflate(R.layout.item_home,viewGroup,false);

  viewHoder.textView = view.findViewById(R.id.tv);

  view.setTag(viewHoder);

  }else {

  viewHoder = (ViewHoder) view.getTag();

  }

  //2.拿到textView,把值传给textView

  // TextView textView = view.findViewById(R.id.tv);

  viewHoder.textView.setText(list.get(i).getName());

  Log.i("TAG", "getView: "+i);

  //3.把view返回出去

  return view;

  }

  }

  private final class ViewHoder{

  TextView textView;

  }

  }