android使用列表视图

  • 内容
  • 评论
  • 相关

主程序文件

package com.example.melistview;

import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
	String[] presidents;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ListView listView = getListView();
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		listView.setTextFilterEnabled(true);
		
		presidents = getResources().getStringArray(R.array.presidents_array);
		setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked,presidents));
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "You Have Select " + presidents[position], Toast.LENGTH_LONG).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public void onClick(View view){
		ListView listView = getListView();
		
		String itemSelected = "item selected \n";
		for(int i = 0; i < listView.getCount(); i++){
			if(listView.isItemChecked(i)){
				itemSelected += listView.getItemAtPosition(i) + "\n";
			}
		}
		Toast.makeText(this, itemSelected, Toast.LENGTH_LONG).show();
	}

}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
<Button android:id="@+id/btn"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Show selected items" 
    android:onClick="onClick"/>

<ListView 
    android:id="@+id/android:list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

效果图

评论

0条评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注