对于很多初学者来说,listview一直是一个难点,刚才整理了一段代码,介绍了listview的使用方式与简单优化,以及item的更新
<1.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:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="60dp" android:text="点我刷新" android:textSize="20.0sp" android:gravity="center" android:id="@+id/update" /> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listview"/></LinearLayout><2.item布局>
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="60dp" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="你好世界" android:textSize="20.0sp" android:gravity="center" android:id="@+id/tv_show"/> </LinearLayout></LinearLayout><3.适配器>
public class MyAdapter extends BaseAdapter { PRivate Context context; private List<String> list; public MyAdapter(List<String> list, Context context) { this.list = list; this.context = context; } @Override public int getCount() { if(list!=null) return list.size(); return 0; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { MyHolder myHolder; if(convertView==null){ myHolder=new MyHolder(); convertView= LayoutInflater.from(context).inflate(R.layout.list_item,null); myHolder.textView= (TextView) convertView.findViewById(R.id.tv_show); convertView.setTag(myHolder); }else { myHolder= (MyHolder) convertView.getTag(); } myHolder.textView.setText(list.get(position).toString()); return convertView; } //listview的一种优化方式 private class MyHolder{ TextView textView; }}<4.源代码>
public class MainActivity extends AppCompatActivity { private ListView listView; private Button button; private MyAdapter myAdapter; private List<String> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); list=new ArrayList<>(); for(int i=0;i<10;i++){ list.add("我是显示文本"+i); } myAdapter=new MyAdapter(list,this); listView.setAdapter(myAdapter); //对刷新按钮添加监听事件 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { list.clear(); for(int i=0;i<10;i++){ list.add("我是更新文本"+i); }//通知适配器改变文本信息 myAdapter.notifyDataSetChanged(); } }); } //实例化控件 private void init(){ listView= (ListView) findViewById(R.id.listview); button= (Button) findViewById(R.id.update); }}希望对你有所帮助
新闻热点
疑难解答