Listview

来源:互联网 发布:js点击调用函数 编辑:程序博客网 时间:2024/06/03 07:14

1.在主activity所对应的xml文件写入代码

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.listview.MainActivity">    <ListView        android:id="@+id/lv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        /></LinearLayout>
2.写listview模板xml文件(model)
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal"    android:layout_width="match_parent"    android:layout_height="match_parent"><TextView    android:id="@+id/tv"    android:layout_width="match_parent"    android:layout_height="match_parent" /></LinearLayout>
3.设置listview适配器
public class MyAdapter extends BaseAdapter {    List<String>  list;    Activity activity;    public MyAdapter(List<String>  list,Activity activity){        this.activity=activity;        this.list=list;    }    @Override    public int getCount() {        return list.size();    }    @Override    public Object getItem(int position) {        return list.get(position);    }    @Override    public long getItemId(int position) {        return position;    }    @Override    public View getView(int position, View convertView, ViewGroup parent) {        //因为要获取Textview所以要先找到模板        View view=(View)activity.getLayoutInflater().inflate(R.layout.modle,null);        TextView textView=(TextView)view.findViewById(R.id.tv);        textView.setText(list.get(position));        return view;    }}
4.在住activity中写入代码
package com.example.listview;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.ListView;import com.example.listview.adapter.MyAdapter;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity {List<String> list;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ListView listView=(ListView)findViewById(R.id.lv);        list=new ArrayList<>();        for(int i=0;i<30;i++){            list.add("jijkhjkmdb"+i);        }        //listView.setAdapter(new MyAdapter(list,this));        MyAdapter myAdapter=new MyAdapter(list,this);        listView.setAdapter(myAdapter);    }}