ListView常用方法-案例介紹
阿新 • • 發佈:2018-10-06
for listen etl i++ from fin ase sim 加載
***ListView的常用方法
實例:設置一個ListView的頁面,其頁面頭部是圖片,尾部是Button按鈕
方式一:
首先在對應的布局文件中添加ListView控件,然後可在主活動文件中對該頁面添加頭部和尾部相應控件,如下:
public class MainActivity extends Activity { private ListView lv; private List<String> list; private ArrayAdapter<String> adapter; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); lv = (ListView) findViewById(R.id.lv); list = new ArrayList<String>(); for (int i = 0; i < 10; i++) { list.add("item"+i); } adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, list); //添加圖片控件 ImageView iv = new ImageView(MainActivity.this); iv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); iv.setImageResource(R.drawable.ic_launcher); lv.addHeaderView(iv);//將參數中指定的控件View添加到ListView的頭部 //註意:addHeaderView()方法必須在setAdapter()方法之前設置 //添加button控件 Button bt = new Button(MainActivity.this); bt.setText("加載更多....."); bt.setTextSize(20); bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int index = list.size(); for (int i = index; i < index+10; i++) { list.add("item"+i); } adapter.notifyDataSetChanged();//該方法是如果適配器的內容改變時強制調用getView來刷新每個Item的內容 } }); lv.addFooterView(bt);//將參數中指定的控件View添加到ListView的尾部 //註意:addFooterView()方法必須在setAdapter()方法之前設置 lv.setAdapter(adapter); lv.setEmptyView(tv); //表示TextView中國如果沒有顯示的數據時顯示參數指定的View視圖 } }
方式二:
當然也可以通過在創建兩個布局文件的形式展示同樣的效果,不需要在主活動文件中直接添加控件,修改如下:
首先在lv_header.xml中添加ImaageView控件,lv_footer.xml中添加Button控件,主布局文件中添加ListView控件
public class OtherActivity extends Activity { private ListView lv; private List<String> list; private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.lv); list = new ArrayList<String>(); for (int i = 0; i < 10; i++) { list.add("item"+i); } adapter = new ArrayAdapter<String>(OtherActivity.this,android.R.layout.simple_list_item_1, list); View headerView = LayoutInflater.from(OtherActivity.this).inflate(R.layout.lv_header, null);//將lv_header.xml布局文件轉換成View視圖 ImageView iv = (ImageView) headerView.findViewById(R.id.iv);//註意:這裏必須通過headerView來調用findViewById方法 iv.setImageResource(R.drawable.bg_us); lv.addHeaderView(iv); View footerView = LayoutInflater.from(OtherActivity.this).inflate(R.layout.lv_footer, null); Button bt = (Button) footerView.findViewById(R.id.bt); bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub int index = list.size(); for (int i = index; i < index+10; i++) { list.add("item"+i); } adapter.notifyDataSetChanged(); } }); lv.addFooterView(bt); lv.setAdapter(adapter); } }
ListView常用方法-案例介紹