Android extended BaseAdapter list items to achieve ListView
table of Contents
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.android20200322.MainActivity">
<ListView
android:id="@+id/myList"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</LinearLayout>
MainActivity
package com.example.administrator.android20200322;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ListView myList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList =(ListView) findViewById(R.id.myList);
BaseAdapter adapter = new BaseAdapter() {
@Override
public int getCount() {
return 40; //指定包含40个选项
}
@Override
public Object getItem(int position) {
return null;
}
//重写该方法,该方法的返回值将作为列表项的ID
@Override
public long getItemId(int position) {
return 0;
}
//重写该方法,该方法返回的View将作为列表框
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 创建一个LinearLayout,并向其中添加两个组件
LinearLayout line = new LinearLayout(MainActivity.this);
line.setOrientation(0);
ImageView image = new ImageView(MainActivity.this);
image.setImageResource(R.drawable.ic_launcher_foreground);
TextView text = new TextView(MainActivity.this);
text.setText("第" + (position+1) + "个列表项");
text.setTextSize(20);
text.setTextColor(Color.RED);
line.addView(image);
line.addView(text);
return line; //返回LinearLayout实例
}
};
myList.setAdapter(adapter);
}
}
getCount (): Returns the value of the Adapter contains control how many list items
getItem (int position): Returns the value determines the content of the list item at the first position
getItemId (int position): Returns the ID value determines the list of items at the first position
getView (int position, View convertView, ViewGroup parent): Returns the value of the component decision list item at the position