第一个月月考练习

权限:

android:name="android.permission.INTERNET" />

依赖:

compile 'com.google.code.gson:gson:2.8.2'
compile 'com.squareup.picasso:picasso:2.5.2'

导入Library

implementation project(':library')

MainActivity布局文件:

xml version="1.0" encoding="utf-8"?>
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"
    android:orientation="vertical"
    tools:context="com.mrzhao.secondweekexamdemo.MainActivity">

            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

                    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:text="用户名:"
            android:textColor="@android:color/black"
            android:textSize="20sp" />

                    android:id="@+id/userName_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:hint="请输入用户名" />


    

            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

                    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:text="密    码:"
            android:textColor="@android:color/black"
            android:textSize="20sp" />

                    android:id="@+id/userPassword_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:hint="请输入密码" />


    

            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

                    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:text="验证密码:"
            android:textColor="@android:color/black"
            android:textSize="20sp" />

                    android:id="@+id/makeSure_password_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:hint="请再次输入密码" />


    

            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

                    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:text="性    别:"
            android:textColor="@android:color/black"
            android:textSize="20sp" />

                    android:id="@+id/userSex_rg"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

                            android:id="@+id/userSex_man"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="男"
                android:textSize="20sp" />

                            android:id="@+id/userSex_woman"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="女"
                android:textSize="20sp" />


        


    

            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

                    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:text="爱    好:"
            android:textColor="@android:color/black"
            android:textSize="20sp" />

                    android:id="@+id/hobby_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

                            android:id="@+id/cb1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="18dp"
                android:text="游戏"
                android:textSize="18sp" />

                            android:id="@+id/cb2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="18dp"
                android:layout_toRightOf="@id/cb1"
                android:text="运动"
                android:textSize="18sp" />

                            android:id="@+id/cb3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="18dp"
                android:layout_toRightOf="@id/cb2"
                android:text="唱歌"
                android:textSize="18sp" />
        
    

            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

                    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:text="地    址:"
            android:textColor="@android:color/black"
            android:textSize="20sp" />

                    android:id="@+id/province_sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp">

                    android:id="@+id/city_sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp">

    

            android:layout_width="match_parent"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_height="wrap_content">
        

MainActivity:

public class MainActivity extends AppCompatActivity {

    private String userName, userPassword, makeSurePassword, userSex, userHobby, userProvince, userCity;
    private EditText userNameEt;
    private EditText userPasswordEt;
    private EditText makeSureEt;
    private RadioGroup userSexRg;
    private RelativeLayout hobbyContainer;
    private Spinner provinceSp;
    private Spinner citySp;

    private CheckBox[] boxes;


    // 省份数据源
    private List provinceList = new ArrayList<>();
    // 城市数据源
    private List cityList = new ArrayList<>();
    // 多个城市数据源
    private List> cityDataList = new ArrayList<>();
    private ArrayAdapter provinceAdapter, cityAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化数据
        initSpinnerData();

        userNameEt = (EditText) findViewById(R.id.userName_et);
        userPasswordEt = (EditText) findViewById(R.id.userPassword_et);
        makeSureEt = (EditText) findViewById(R.id.makeSure_password_et);

        userSexRg = (RadioGroup) findViewById(R.id.userSex_rg);
        hobbyContainer = (RelativeLayout) findViewById(R.id.hobby_container);
        boxes = new CheckBox[hobbyContainer.getChildCount()];
        //实例化所有CheckBox 的过程
        for (int i = 0; i < boxes.length; i++) {
            boxes[i] = (CheckBox) hobbyContainer.getChildAt(i);
        }


        provinceSp = (Spinner) findViewById(R.id.province_sp);
        citySp = (Spinner) findViewById(R.id.city_sp);

        //初始化适配器
        provinceAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, provinceList);
        cityAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, cityList);

        //设置适配器
        provinceSp.setAdapter(provinceAdapter);
        citySp.setAdapter(cityAdapter);

        //获取用户性别
        userSexRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.userSex_man:
                        userSex = "男";
                        break;
                    case R.id.userSex_woman:
                        userSex = "女";
                        break;
                }
            }
        });

        //省份监听器
        provinceSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView parent, View view, int position, long id) {
                //获取选中的省份
                userProvince = provinceList.get(position);
                //清空城市数据
                cityList.clear();
                cityList.addAll(cityDataList.get(position));
                //刷新数据
                cityAdapter.notifyDataSetChanged();
                citySp.setSelection(0);
                //修改默认城市数据
                userCity = cityList.get(0);
            }

            @Override
            public void onNothingSelected(AdapterView parent) {

            }
        });
        //城市监听器
        citySp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView parent, View view, int position, long id) {
                //用户城市
                userCity = cityList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView parent) {

            }
        });
    }


    public void onClick(View view) {
        //点击注册
        userName = userNameEt.getText().toString();
        userPassword = userPasswordEt.getText().toString();
        makeSurePassword = makeSureEt.getText().toString();

        if (TextUtils.isEmpty(userName)) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(userPassword)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(makeSurePassword)) {
            Toast.makeText(this, "请输入确认密码", Toast.LENGTH_SHORT).show();
            return;
        }

        // 判断 两次密码一致
        if (!userPassword.equals(makeSurePassword)) {
            Toast.makeText(this, "两次密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        //获取用户爱好
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < boxes.length; i++) {
            if (boxes[i].isChecked()) {
                buffer.append(boxes[i].getText().toString() + " ");
            }
        }
        //获取用户爱好
        userHobby = buffer.toString();


        //传递数据到第二个页面
        Intent intent = new Intent(this, InfoActivity.class);
        intent.putExtra("userName", userName);
        intent.putExtra("userPassword", userPassword);
        intent.putExtra("userMakeSure", makeSurePassword);
        intent.putExtra("userSex", userSex);
        intent.putExtra("userHobby", userHobby);
        intent.putExtra("userProvince", userProvince);
        intent.putExtra("userCity", userCity);

        //为了一个结果而传递数据 启动Activity
        startActivityForResult(intent, 10000);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10000 && resultCode == 10001) {
            String info = data.getStringExtra("info");
            Toast.makeText(this, info, Toast.LENGTH_SHORT).show();
        }
    }

    //初始化  Spinner 的数据 省份和 城市的
    private void initSpinnerData() {
        provinceList.add("北京");
        provinceList.add("河北");

        // 城市
        List beijing = new ArrayList<>();
        beijing.add("海淀区");
        beijing.add("东城区");

        List hebei = new ArrayList<>();
        hebei.add("廊坊");
        hebei.add("石家庄");

        //城市数据源
        cityDataList.add(beijing);
        cityDataList.add(hebei);

        //默认城市
        cityList.addAll(cityDataList.get(0));

    }

    public void onUserClick(View view) {
        //点击跳转到第三个页面
        Intent intent = new Intent(this, HomeActivity.class);
        intent.putExtra("userName", userName);
        intent.putExtra("userPassword", userPassword);
        intent.putExtra("userMakeSure", makeSurePassword);
        intent.putExtra("userSex", userSex);
        intent.putExtra("userHobby", userHobby);
        intent.putExtra("userProvince", userProvince);
        intent.putExtra("userCity", userCity);

        //为了一个结果而传递数据 启动Activity
        startActivity(intent);

    }
}

InfoActivity布局文件:

xml version="1.0" encoding="utf-8"?>
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:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.mrzhao.secondweekexamdemo.InfoActivity">




InfoActivity:

public class InfoActivity extends AppCompatActivity {

    private LinearLayout container;
    private List list = new ArrayList<>();
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);


        final Intent intent = getIntent();
        String userName = intent.getStringExtra("userName");
        String userPassword = intent.getStringExtra("userPassword");
        String userMakeSure = intent.getStringExtra("userMakeSure");
        String userSex = intent.getStringExtra("userSex");
        String userHobby = intent.getStringExtra("userHobby");
        String userProvince = intent.getStringExtra("userProvince");
        String userCity = intent.getStringExtra("userCity");

        list.add(userName);
        list.add(userPassword);
        list.add(userSex);
        list.add(userHobby);
        list.add(userProvince);
        list.add(userCity);

        container = (LinearLayout) findViewById(R.id.container);

        for (int i = 0; i < list.size(); i++) {

            TextView view = new TextView(this);
            view.setText(list.get(i));
            view.setTextSize(20);
            view.setPadding(10, 10, 10, 10);
            container.addView(view);
        }

        button = new Button(this);
        button.setText("返回");
        container.addView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置结束结果返回值
                Intent  intent1 = new Intent();
                intent1.putExtra("info","注册成功");
                setResult(10001,intent1);
                finish();
            }
        });
    }
}

HomeActivity布局文件:

xml version="1.0" encoding="utf-8"?>
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="com.mrzhao.secondweekexamdemo.HomeActivity">

            android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">



HomeActivity:

public class HomeActivity extends AppCompatActivity {

    private PullToRefreshListView listView;

    private String path = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=";
    private int pager = 1;
    private Gson gson;
    private List list = new ArrayList<>();
    private MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        //获取注册信息
        Intent intent = getIntent();
        String userName = intent.getStringExtra("userName");
        String userPassword = intent.getStringExtra("userPassword");
        String userMakeSure = intent.getStringExtra("userMakeSure");
        String userSex = intent.getStringExtra("userSex");
        String userHobby = intent.getStringExtra("userHobby");
        String userProvince = intent.getStringExtra("userProvince");
        String userCity = intent.getStringExtra("userCity");
        //吐司展示用户信息
        Toast.makeText(this, userName + "_" + userPassword + "_" + userSex + "_" + userHobby + "_" + userProvince + ":" + userCity, Toast.LENGTH_SHORT).show();
        //可刷新的ListView
        listView = (PullToRefreshListView) findViewById(R.id.listView);
        listView.setMode(PullToRefreshBase.Mode.BOTH);
        //实例化解析
        gson = new Gson();
        //设置适配器
        myAdapter = new MyAdapter(list, this);
        listView.setAdapter(myAdapter);
        //启动异步任务下载数据
        new MyTask().execute();
        // 设置下拉刷新和上拉加载更多监听器
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                //下拉刷新 清空数据
                list.clear();
                pager=1;
                new MyTask().execute();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {
                // 加载更多
                pager++;
                new MyTask().execute();
            }
        });

        //点击条目 下载图片放大展示
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                //点击获取条目 的图片地址传递到下一个页面
                Intent  intent1 = new Intent(HomeActivity.this, ImageActivity.class);
                intent1.putExtra("pic_url",  list.get(position-1).getPic());
                startActivity(intent1);
            }
        });

    }

    //异步任务
    class MyTask extends AsyncTask, Void, String> {
        @Override
        protected String doInBackground(String... strings) {
            // 获取网络数据
            return getDataFromNet();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //设置刷新状态完成
            listView.onRefreshComplete();
            if (!TextUtils.isEmpty(s)){
                // 解析
                FoodEntity foodEntity = gson.fromJson(s, FoodEntity.class);
                List data = foodEntity.getData();
                list.addAll(data);
                //刷新适配器
                myAdapter.notifyDataSetChanged();
            }
        }
    }

    //从网络获取数据
    private String getDataFromNet() {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            URL url = new URL(path + pager);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            conn.setConnectTimeout(20 * 1000);
            conn.setReadTimeout(20 * 1000);
            conn.connect();
            if (conn.getResponseCode() == 200) {
                inputStream = conn.getInputStream();
                outputStream = new ByteArrayOutputStream();
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
                return outputStream.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

item条目布局文件:

xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

            android:id="@+id/food_pic_iv"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="10dp" />

    <LinearLayout
        android:layout_width="match_parent"
android:layout_marginTop="10dp"
        android:layout_height="wrap_content"
        android:orientation="vertical">

                    android:id="@+id/food_title_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:textSize="20sp" />

                    android:id="@+id/food_str_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp" />
    LinearLayout>
LinearLayout>

适配器MyAdapter:

public class MyAdapter extends BaseAdapter {
    private List list;
    private Context context;
    private LayoutInflater inflater;

    public MyAdapter(List list, Context context) {
        this.list = list;
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null){
            convertView  =  inflater.inflate(R.layout.item_layout,parent,false);
            holder = new ViewHolder();
            holder.foodPicIv =  convertView.findViewById(R.id.food_pic_iv);
            holder.foodTitleTv =  convertView.findViewById(R.id.food_title_tv);
            holder.foodStrTv =  convertView.findViewById(R.id.food_str_tv);
            convertView.setTag(holder);
        }else {
            holder   = (ViewHolder) convertView.getTag();
        }
        FoodEntity.DataBean dataBean = list.get(position);

        holder.foodTitleTv.setText(dataBean.getTitle());
        holder.foodStrTv.setText(dataBean.getFood_str());
        Picasso.with(context).load(dataBean.getPic()).into(holder.foodPicIv);

        return convertView;
    }

    static class ViewHolder {
        ImageView foodPicIv;
        TextView foodTitleTv;
        TextView foodStrTv;
    }
}

ImageActivity布局文件:

xml version="1.0" encoding="utf-8"?>
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="com.mrzhao.secondweekexamdemo.ImageActivity">

            android:id="@+id/show_iv"
        android:background="@android:color/black"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


ImageActivity:

public class ImageActivity extends AppCompatActivity {

    private ImageView showIv;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);
        Intent intent = getIntent();
        //获取传递过来的图片地址
        String pic_url = intent.getStringExtra("pic_url");
        showIv = (ImageView) findViewById(R.id.show_iv);
        //初始化 进度弹出框
        dialog = new ProgressDialog(this);

        dialog.setMax(100);
        dialog.setTitle("提示");
        dialog.setIcon(R.mipmap.ic_launcher);
        //设置 水平样式
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //执行图片下载异步任务
        new ImageTask().execute(pic_url);
        //设置图片监听器 当点击的时候销毁这个页面
        showIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    class ImageTask extends AsyncTask, Integer, Bitmap> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //开始的时候 展示弹出框
            dialog.show();
        }

        @Override
        protected Bitmap doInBackground(String... strings) {
            InputStream inputStream = null;
            ByteArrayOutputStream outputStream = null;
            try {
                //下载图片
                URL url = new URL(strings[0]);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setReadTimeout(10 * 1000);
                conn.setConnectTimeout(10 * 1000);
                //获取图片总大小
                int total = conn.getContentLength();
                conn.connect();
                if (conn.getResponseCode() == 200) {
                    inputStream = conn.getInputStream();
                    outputStream = new ByteArrayOutputStream();
                    int len = 0;
                    // 记录 已经下载了多少
                    int current = 0;
                    byte[] bytes = new byte[1024];
                    while ((len = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, len);
                        // 模拟下载过程
                        Thread.sleep(100);
                        current += len;
                        //计算进度
                        int progress = (int) (current / (float) total * 100);
                        publishProgress(progress);
                    }
                    byte[] imageBytes = outputStream.toByteArray();
                    // 图片
                    Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
                    return bitmap;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            //更新进度
            dialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            //关闭 弹出框
            dialog.dismiss();
            if (bitmap != null) {
                //设置图片
                showIv.setImageBitmap(bitmap);
            }
        }
    }
}


你可能感兴趣的:(Android课程练习,Android)