zoukankan      html  css  js  c++  java
  • arrayAdapter

    1.可以通过在values文件夹中定义数组文件arrays.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string-array name="books">
            <item>java讲义</item>
            <item>android讲义</item>
            <item>ajax讲义</item>
            <item>.net讲义</item>
            
        </string-array>
    </resources>

    main.xml文件只需要这么写

    <!-- 直接使用数组资源给出列表项 -->
    
        <ListView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:divider="@drawable/red"
            android:entries="@array/books"
            android:headerDividersEnabled="true" />

    android:entries这句话是导入数组文件的,java代码不需要做任何处理,只需要一句话setContentView(R.layout.main);

    2.方式二是通过代码形式

    main.xml

    <ListView
            android:id="@+id/list2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:divider="@drawable/green" />

    java代码

    ListView list2 = (ListView)findViewById(R.id.list2);
            //定义一个数组
            String[] arr ={"孙悟空" , "猪八戒" , "牛魔王"};
            //将数组包装ArrayAdapter
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this , android.R.layout.simple_list_item_1 , arr);
            //为ListView设置Adapter
            list2.setAdapter(arrayAdapter);    

    当然这2种方式可以写在一个布局文件main.xml中

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:divider="@drawable/red"
            android:entries="@array/books"
            android:headerDividersEnabled="true" />
    
        <ListView
            android:id="@+id/lv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:divider="@drawable/blue" />
    
    </LinearLayout>

    java代码如下

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            ListView lv = (ListView) findViewById(R.id.lv);
            String[] str = { "hello", "world", "!!!" };
            lv.setAdapter(new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, str));
    
        }
    运行效果图如下

  • 相关阅读:
    消息队列接口API(posix 接口和 system v接口)
    Ubuntu 安装 Eclipse C/C++开发环境
    Ubuntu下Eclipse搭建ARM开发环境
    Linux进程间通信——使用流套接字
    Linux进程间通信——使用数据报套接字
    Linux进程间通信——信号集函数
    Linux进程间通信——使用信号
    Linux进程间通信——使用匿名管道
    mappedBy的作用
    VS Code 配置 C/C++ 环境
  • 原文地址:https://www.cnblogs.com/android-zcq/p/3278037.html
Copyright © 2011-2022 走看看