Android開發案例 點選按鈕出現 簡易的訊息提示框

2020-09-22 15:01:58

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list"></ListView>

</LinearLayout>

 

package com.example.administrator.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //建立資料來源
        final String[] data={
                "選項一",
                "選項二",
                "選項三",
                "選項四",
                "選項五",
                "選項六",
                "選項七"
        };
        //把資料來源儲存到adpter
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,data);
        //把資料設定到檢視
        ListView listView = (ListView)findViewById(R.id.list);
        listView.setAdapter(arrayAdapter);
        //設定彈窗
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,data[position],Toast.LENGTH_SHORT).show();
            }
        });
    }
}