android ListView的使用

在Acvitity中显示要显示列表,并且显示相应内容:

public class MainActivity extends Activity {
 private static final String[] array = {
  "sunday","monday","tuesday","wednesday",
  "thursday","friday","saturday"
 };
 
 private LinearLayout myLinearLayout;
 private TextView myTextView;
 private ListView myListView;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        //创建一个布局器
        myLinearLayout = new LinearLayout(this);
        myLinearLayout.setBackgroundColor(android.graphics.Color.WHITE);
        myLinearLayout.setOrientation(LinearLayout.VERTICAL);
       
        //添加TextView
        myTextView = new TextView(this);
        LinearLayout.LayoutParams param1 = new LinearLayout.LayoutParams(
          LinearLayout.LayoutParams.FILL_PARENT,
          LinearLayout.LayoutParams.WRAP_CONTENT
        );
        myTextView.setText(R.string.title);
        myTextView.setBackgroundColor(getResources().getColor(R.drawable.blue));
        myLinearLayout.addView(myTextView, param1);
       
        //创建ListView
        myListView = new ListView(this);
        LinearLayout.LayoutParams param2 = new LinearLayout.LayoutParams(
          LinearLayout.LayoutParams.FILL_PARENT,
          LinearLayout.LayoutParams.WRAP_CONTENT
        );
        myListView.setBackgroundColor(getResources().getColor(R.drawable.ltgray));
        myLinearLayout.addView(myListView, param2);
       
        //new ArrayAdapter对象,并将数据传入
        ArrayAdapter arrAdapter = new ArrayAdapter
             (this, R.layout.my_simple_list_item, array);
        myListView.setAdapter(arrAdapter);

 

       setContentView(myLinearLayout);
        
      //====================================================================================
       
        //添加鼠标滚轮选中后出发事件OnItemSelectedListener
        myListView.setOnItemSelectedListener(new OnItemSelectedListener() {

   public void onItemSelected(AdapterView arg0, View arg1,
     int arg2, long arg3) {
    //将鼠标滚轮选中的item的字符串内容显示到myTextView上
    myTextView.setText("你选的是" + arg0.getSelectedItem().toString());
    
   }

   public void onNothingSelected(AdapterView arg0) {
    // TODO Auto-generated method stub
    
   }
         
        });
       
        //添加鼠标单击事件
        myListView.setOnItemClickListener(new OnItemClickListener() {

   public void onItemClick(AdapterView arg0, View arg1, int arg2,
     long arg3) {
    //arg2是ListView的index
    myTextView.setText("你选中的是" + array[arg2]);
    
   }
         
        });
    }
}

你可能感兴趣的:(android ListView的使用)