android ListView 示例5 使用 BaseAdapter 创建 ListView

首先创建自定义的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/myList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>

之后创建编写Activity文件如下:

package com.toby.personal.testlistview;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
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 Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView listView = (ListView) findViewById(R.id.myList);

        BaseAdapter adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return 40;
            }

            @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) {

                LinearLayout layout = new LinearLayout(MainActivity.this);
                layout.setOrientation(LinearLayout.HORIZONTAL);
                ImageView imageView = new ImageView(MainActivity.this);
                imageView.setImageResource(R.drawable.ic_launcher);
                TextView textView = new TextView(MainActivity.this);
                textView.setText("No." + (i+1) + " list item.");
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
                textView.setTextColor(Color.GRAY);
                layout.addView(imageView);
                layout.addView(textView);

                return layout;
            }
        };

        listView.setAdapter(adapter);
    }
}

参考文献:《疯狂Android讲义(第2版)》

    原文作者:赵者也
    原文地址: https://www.jianshu.com/p/45d5da020d32
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞