• eatwhatApp开发实战(二)


    上期,我们做了个小app“eatwhat”,接下来每期都会为其添加新的功能。本期,我们为店铺增加添加店铺的功能。

      还是先设置个布局:
        <RelativeLayout 
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    	        <Button 
    		    android:id="@+id/add_shop_btn"
    		    android:layout_width="wrap_content"
    		    android:layout_height="wrap_content"
    		    android:layout_alignParentRight="true"
    		    android:text="@string/add_shop_btn_text"
    		    android:onClick="addShop"/>
    		<EditText 
    		    android:id="@+id/addshop_et"
    		    android:layout_width="match_parent"
    		    android:layout_height="wrap_content"
    		    android:layout_toLeftOf="@id/add_shop_btn"
    		    android:textSize="18sp"/>
        </RelativeLayout>
    
      得到这个界面:

      这里我们换种按钮点击事件的写法:
    android:onClick="addShop"/>
    
      同时在java代码中定义一个方法:
        public void addShop(View view){
    }
      这里注意,方法名得和之前设置add_shop_btn里面onClick的方法名一致。
      接下来定义一个shopName的集合和addshop_et的EditText(文本框)
    private List<String> shopNameList;
    
      在init()方法里面初始化
    //定义一个集合用来存放我们要的几个店名
    shopNameList = new ArrayList<String>();
    		
    //初始化控件addshop_EditText
    addshop_et = (EditText) findViewById(R.id.addshop_et);
    
       在addShop()方法中写添加逻辑:
    String addName = addshop_et.getText().toString();
    if (addName == null||addName == ""){
      Toast.makeText(MainActivity.this, "添加内容为空", Toast.LENGTH_SHORT).show();
    } else{
      //List shop添加店名
      shopNameList.add(addName);
      //清空文本框内容
      addshop_et.setText("");
      String toast_text = "添加店铺:" + addName;
      Toast.makeText(MainActivity.this, toast_text, Toast.LENGTH_SHORT).show();
    }
    
      之后修改之前的RandomBtnClick内部类的点击事件
    if (shopNameList.size()==0){
        Toast.makeText(MainActivity.this,"店家列表为空,你还未添加店家",     Toast.LENGTH_SHORT).show();
    }else{
        //随机数
        Random random = new Random();
        //获取shopNameList长度来设置随机区间
        int num = random.nextInt(shopNameList.size());
        //textview显示以该随机数对应的商家集合的名字
        shop_name.setText(shopNameList.get(num));
    }
    
      这样,我们就把添加店家这个功能添加到eatwhatApp中
  • 相关阅读:
    react Native 运行报错之一 gradle-2.14.1-all解压失败的问题
    react native windows create bundle folder
    gulp+browserSync+nodemon 实现express 全端自动刷新的实践
    nodejs框架express4.x 学习--安装篇
    转: angularjs 指令中动态编译的方法(适用于有异步请求的情况) 内嵌指令无效
    angular 基础练习
    自己写的数组排重+排序
    前端开发bower包管理器
    定位网站性能的一些经验
    记一次大规模数据迁移和加密
  • 原文地址:https://www.cnblogs.com/superdo/p/5005314.html
Copyright © 2020-2023  润新知