ListView是Android中一種條列式顯示的控制項,
主要使用ListView與ArrayAdapter來顯示,
下列的程式為將要顯示的項目放入Array中,
然後將這一個Array放入ArrayAdpater,
之後再將listview.setAdapter方法,將 ArrayAdpater 放入,
1. Layout
2. Android code:
package com.example.codelistview;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ListView listView;
private String[] list = {"菜園","果園","動物園","海底樂園"};
private ArrayAdapter<String> listAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView1);
listAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Toast.makeText(getApplicationContext(), "你點選的項目是" + list[position], Toast.LENGTH_SHORT).show();
}
});
}
3. Android手機顯示:
留言列表