ListView元件應用

1.UI的xml檔
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
   <ListView
       android:id="@+id/list"
       android:layout_width="100pt"
       android:layout_height="100pt"
       android:layout_alignParentLeft="true"
       android:layout_centerVertical="true"
       android:layout_marginLeft="26dp"
       >
   </ListView>
</RelativeLayout>
2.主程式程式碼
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
String[] data = { "Android 第一講", "Android 第二講", "Android 第三講",
"Android 第四講", "Android 第五講", "Android 第六講", "Android 第七講" };
ListView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setView();
view.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"您點擊的是:" + ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
// 為ListView 設置長按監聽器
view.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"您長按的是:" + ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
return false;
}
});
}
public void setView() {
view = (ListView) this.findViewById(R.id.list);
view.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, data));
}
}

沒有留言: