跳到主要內容

Android--ListView的範例

package com.example.test_app03;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.view.*;
import android.widget.AdapterView;

public class MainActivity extends Activity {
    
     private ListView listView01;
     private String[] show_text = {"未帶鑰匙","網路問題","電腦故障","商店","診所"};
     private ArrayAdapter listAdapter;
    private TextView textView01;
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);         
         
          listView01 = (ListView)findViewById(R.id.listView1);
         
          //把show_text放進來,讓ListView直接用陣列的值
          listAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,show_text);
          listView01.setAdapter(listAdapter);
         
          //ListView的onClick
          listView01.setOnItemClickListener(new OnItemClickListener(){
                 @Override
                 public void onItemClick(AdapterView parent, View view, int position, long id){
                    Toast.makeText(getApplicationContext(),                                                                   
                                     "點選的是"+show_text[position], //postition是指點選到的index
                                        Toast.LENGTH_SHORT).show();
                    listView01.setVisibility(view.INVISIBLE); //隱藏ListView
                 } //end onItemClick
          }); //end setOnItemClickListener
         
     }

     @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;
     }

}


留言