• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

gisoracle

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

andriod listview

activity_main.xml

<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView android:text="请点餐!" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/msgTxv"
        android:textSize="22sp" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lv"
        android:entries="@array/menuItems" />

</LinearLayout>

 MainActivity.java

package com.example.yanlei.myapplication;

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.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 获取 ListView 对象, 并设置按下操作的监听器
        ListView lv=(ListView) findViewById(R.id.lv);
        lv.setOnItemClickListener(this);
    }

    // 存储当前选取的选项 (餐点) 名称字符串
    ArrayList<String> selected= new ArrayList<>();

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView txv = (TextView) view; // 将被单击的 View 对象转成 TextView
        String item=txv.getText().toString();

        if(selected.contains(item)) // 若 ArrayList 已有同名选项
            selected.remove(item);  // 就将它删除
        else                        // 若 ArrayList 没有同名选项
            selected.add(item);     // 就将它加到 ArrayList (当成选取的选项)

        String msg;
        if(selected.size()>0){   // 若 ArrayList 中的选项数大于 0
            msg="你点了:";
            for(String str:selected)
                msg+=" "+str;    // 每个选项 (餐点) 名称前空一格
        }                        // 并附加到信息字符串后面
        else                     // 若 ArrayList 中的选项数等于 0
            msg="请点餐!";

        TextView msgTxv =(TextView) findViewById(R.id.msgTxv);
        msgTxv.setText(msg);  // 显示信息字符串
    }

}

 

posted on 2017-10-04 09:20  gisai  阅读(146)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3