先弄程式碼,怕今天太晚回來
MainActivity.java 部分
//package tw.com.fantasylin.listviewdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
String[] foods={"麵線","魯肉飯","小籠包","珍奶","肉包","雞排","便當","大冰奶","原來氏你","舒跑","咖啡"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
}
private void findViews(){
ListView listView=(ListView)findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,foods));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,foods[position], Toast.LENGTH_SHORT).show();
}
});
}
}
activity_main.xml 部分
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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="tw.com.fantasylin.listviewdemo.MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp">
</ListView>
</RelativeLayout>