ListView

以上下滑动的形式显示多项同类型内容

效果如下(图片资源来自网络)


ListView_第1张图片

可以通过滑动的方式浏览水果的图片


代码如下


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

在主活动创建一个ListView控件


<ImageView
        android:id="@+id/fruit_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"
        />

新建一个fruit.xml用来添加到主布局的ListView

public class MainActivity extends AppCompatActivity
{
    private List fruitList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruits();  //初始化水果数据
        //初始化适配器,存放fruit_item.xml布局
        FruitAdapter adapter = new FruitAdapter(MainActivity.this, R.layout.fruit_item, fruitList);
        ListView listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id)
            {
                Fruit fruit = fruitList.get(position);
                Toast.makeText(MainActivity.this, fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initFruits()
    {
        for(int i = 0; i < 2; i++)
        {
            Fruit apple = new Fruit("Apple", R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit("Banana", R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit pear = new Fruit("Pear", R.drawable.pear_pic);
            fruitList.add(pear);
            Fruit grape = new Fruit("Grape", R.drawable.grape_pic);
            fruitList.add(grape);
            Fruit watermelon = new Fruit("Watermelon", R.drawable.watermelon_pic);
            fruitList.add(watermelon);
        }
    }
}

首先创建一个fruitList用来存放这几种Fruit,然后在onCreate() 方法中listView.setAdapter(adapter)初始化适配器,初始化后的适配器用listView.setAdapter(adapter)添加到ListView,用listView.setOnItemClickListener() 添加监听器。

你可能感兴趣的:(Android学习日记,android,布局,listview)