天天看點

Android入門之ListView(純java)

Android入門之ListView(純java)
Android入門之ListView(純java)
Android入門之ListView(純java)
import java.util.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

/*
 * 本例展示了3種清單
 * 1、主清單mainView:單字元串單行顯示,simple_list_item_1,
 * 2、子清單1,lv1:雙字元串雙行顯示,simple_list_item_2
 * 3、子清單2,lv2:自定義顯示,多View
 */

public class ListViewTest extends Activity {
	
	private ListView mainView=null;
	private ListView myList1=null;
	private ListView myList2=null;
	private SimpleAdapter sa=null;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainView_init();
        setContentView(mainView);
    }
    
    /*mainView初始化*/
    void mainView_init(){
    	mainView=new ListView(this);
        mainView.setLayoutParams(new LinearLayout.LayoutParams(-1,-1));
        //主清單是采用ArrayAdapter實作
        String[] strList={"simple_list_item_2","自定義"};
        ArrayAdapter<String> aa=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,strList);
        mainView.setAdapter(aa);
        //綁定監聽
        mainView.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,long arg3) {
				if(index==0){
					if(myList1==null){
						myList1_init();
					}
					setContentView(myList1);
				}else if(index==1){
					if(myList1==null){
						myList2_init();
					}
					setContentView(myList2);
				}
			}
        });
    }
    /*sa初始化*/
    void sa_init(){
    	List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
    	Map<String,Object> item;
    	item=new HashMap<String,Object>();
    	item.put("姓名","張三同學");
    	item.put("性别","男");
    	list.add(item);
    	item=new HashMap<String,Object>();
    	item.put("姓名","李四同學");
    	item.put("性别","男");
    	list.add(item);
    	item=new HashMap<String,Object>();
    	item.put("姓名","小蘭同學");
    	item.put("性别","女");
    	list.add(item);
    	//
    	String str[]={"姓名","性别"};
    	int id[]={android.R.id.text1,android.R.id.text2};//view由系統系統提供的
    	//
    	sa=new SimpleAdapter(this,list,android.R.layout.simple_list_item_2,str,id);
    }
    /*myList1初始化*/
    void myList1_init(){
    	myList1=new ListView(this);
    	myList1.setLayoutParams(new LinearLayout.LayoutParams(-1,-1));
    	sa_init();
    	myList1.setAdapter(sa);
    }
    /*myList2初始化*/
    void myList2_init(){
    	myList2=new ListView(this);
    	myList2.setLayoutParams(new LinearLayout.LayoutParams(-1,-1));
        //自定義MyAapter,見下篇
     	MyAdapter ma=new MyAdapter(this);
     	myList2.setAdapter(ma);
    }
}


           

繼續閱讀