ListView使用实例
实现一个列表,其中显示班级学号姓名,提供添加功能,如需要删去某一项,长按该项,通过弹出菜单显示删除功能。
1.界面布局
2.Button点击事件
Button click = (Button)findViewById(R.id.button);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText a=(EditText) findViewById(R.id.edit1);
EditText b=(EditText)findViewById(R.id.edit2);
EditText c=(EditText)findViewById(R.id.edit3);
ArrayAdapter<String> temp=(ArrayAdapter<String>)list.getAdapter();
temp.add(a.getText().toString()+" "+b.getText().toString()+" "+c.getText().toString());
}
});
3.ListView适配器
final ListView list= (ListView) findViewById(R.id.list);
List<String> lists= new ArrayList<String>();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,lists);
list.setAdapter(adapter);
4.Popupmenu点击事件
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, final int it, long ls) {
if(ls > 0)
{
PopupMenu popup = new PopupMenu(MainActivity.this,view);
popup.getMenuInflater().inflate(R.menu.popupmenu,popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
@Override
public boolean onMenuItemClick(MenuItem item){
switch (item.getItemId()){
case R.id.popupmenu:
ArrayAdapter temp_adp = (ArrayAdapter) list.getAdapter();
temp_adp.remove(temp_adp.getItem(it));
return true;
default:
return false;
}
}
});
}
}
});
5.Popumenu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="50dp"
>
<item
android:id="@+id/popupmenu"
android:orderInCategory="100"
android:title="删除">
</item>
</menu>
总结
ListView能够通过适配器将数据和显示控件绑定,在有限的屏幕上提供大量内容上的选择,支持点击事件,可以用少量代码实现复杂选择功能。