安卓开发学习笔记

安卓开发

安卓学习笔记。对应b站视频

常见布局

  • 线性布局 LinearLayout

如果使用了权重,通常设元素宽度为0,否则会冲突以width为主。

image-20210430133850330
  • 相对布局 RelativeLayout

在这里插入图片描述

  • 表格布局 TableLayout
  • 帧布局 FrameLayout

常用控件

TextView

image-20210430145643457image-20210430145700244image-20210430145815907

Button

  • 点击事件写法Ⅰ

    ​ 通过按钮的onClick指定点击事件出发的方法,方法在对应的activity中实现。

    image-20210430151833275
  • 点击事件写法Ⅱ

    ​ 通过匿名内部类的方式是实现。

    image-20210430152558030

ImageView

image-20210430153313815

EditView

image-20210430153805905

Toast

image-20210430155711173

CheckBox

image-20210430163741310
package com.example.hellp.activitys;

import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.hellp.R;

public class MainActivity extends AppCompatActivity {

    private CheckBox cb1, cb2, cb3;
    private String hobbies;
    private String msg1, msg2, msg3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        initView();
        setView();
    }

    private void setView() {
        //监听器
        CompoundButton.OnCheckedChangeListener occl = new CompoundButton.OnCheckedChangeListener() {
            @Override
            //buttonView传递的是checkBox对象,isChecked传递的是是否被选中
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (buttonView.getId()==R.id.cb1){
                    if (isChecked){
                        msg1 = buttonView.getText().toString();
                    }else {
                        msg1 = "";
                    }
                }
                if (buttonView.getId()==R.id.cb2){
                    if (isChecked){
                        msg2 = buttonView.getText().toString();
                    }else {
                        msg2 = "";
                    }
                }
                if (buttonView.getId()==R.id.cb3){
                    if (isChecked){
                        msg3 = buttonView.getText().toString();
                    }else {
                        msg3 = "";
                    }
                }

                Toast.makeText(MainActivity.this, msg1+msg2+msg3, Toast.LENGTH_SHORT).show();
            }
        };

        cb1.setOnCheckedChangeListener(occl);
        cb2.setOnCheckedChangeListener(occl);
        cb3.setOnCheckedChangeListener(occl);
    }

    private void initView() {
        cb1 = findViewById(R.id.cb1);
        cb2 = findViewById(R.id.cb2);
        cb3 = findViewById(R.id.cb3);
    }
}
<?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=".activitys.MainActivity"
    android:gravity="center_horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="爱好"/>

    <CheckBox
        android:id="@+id/cb1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="游泳"/>
    <CheckBox
        android:id="@+id/cb2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="唱歌"/>
    <CheckBox
        android:id="@+id/cb3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳舞"/>


</LinearLayout>
  • AlertDialog对话框
image-20210430163846179
  • 带【确定】【取消】按钮的对话框
image-20210501095548529
package com.example.hellp.activitys;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import com.example.hellp.R;

public class MainActivity extends AppCompatActivity {

    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        initView();
        setView();
    }

    private void setView() {
       btn.setOnClickListener(new View.OnClickListener() {
           //点击按钮弹出一个对话框
           @Override
           public void onClick(View v) {
               //1、创建对话框的builder对象
               AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
               //2、该对象用于构建一个对话框模板
               builder.setIcon(R.mipmap.ic_launcher)
                       .setTitle("退出!")
                       .setMessage("确定要推出吗?再玩会儿?")
                       .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                                //关闭当前对话框
                                dialog.dismiss();
                                //关闭这个app
                               MainActivity.this.finish();
                           }
                       })
                       .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               //关闭当前对话框
                               dialog.dismiss();
                           }
                       });
               //3、builder对象调用create()方法创建一个对话框对象
               AlertDialog alertDialog = builder.create();
               //4、该对象调用show()方法就可以运行了
               alertDialog.show();
           }
       });
    }

    private void initView() {
        btn = findViewById(R.id.btn);
    }
}
<?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=".activitys.MainActivity"
    android:padding="20dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="退出" />
    </LinearLayout>
</LinearLayout>
  • 带【单选】的对话框
image-20210501102340399
package com.example.hellp.activitys;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.hellp.R;

public class MainActivity extends AppCompatActivity {

    private Button btn;
    private TextView tv;
    private int index=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        initView();
        setView();
    }

    private void setView() {
        String[] showMsg = new String[]{"小号","中号","大号","超大号"};
        int[] textSize = new int[]{10, 20, 30, 40};
       btn.setOnClickListener(new View.OnClickListener() {
           //点击按钮弹出一个对话框
           @Override
           public void onClick(View v) {
               //1、创建对话框的builder对象
               AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
               //2、该对象用于构建一个对话框模板
               builder.setIcon(R.mipmap.ic_launcher)
                       .setTitle("修改文本大小")
                       //第一个参数:显示的选项;第二个参数:默认选中第几个;第三个参数:监听事件
                       .setSingleChoiceItems(showMsg, index, new DialogInterface.OnClickListener() {
                           @Override
                           //which:选择了哪项就返回这一项的序号
                           public void onClick(DialogInterface dialog, int which) {
                                index = which;
                           }
                       })
                       .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               tv.setTextSize(textSize[index]);
                           }
                       })
                       .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               //关闭当前对话框
                               dialog.dismiss();
                           }
                       });
               //3、builder对象调用create()方法创建一个对话框对象
               AlertDialog alertDialog = builder.create();
               //4、该对象调用show()方法就可以运行了
               alertDialog.show();
           }
       });
    }

    private void initView() {
        btn = findViewById(R.id.btn);
        tv = findViewById(R.id.tv);
    }
}
<?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=".activitys.MainActivity"
    android:padding="20dp">

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

        <TextView
            android:id="@+id/tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="我是文本框"
            android:textSize="30dp"
            android:gravity="center_horizontal"/>

        <Button
            android:id="@+id/btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="设置文本大小" />
    </LinearLayout>
</LinearLayout>
  • 带【多选】的对话框
image-20210501103636686
package com.example.hellp.activitys;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.hellp.R;

public class MainActivity extends AppCompatActivity {

    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        initView();
        setView();
    }

    private void setView() {
        String[] showMsg = new String[]{"唱歌","跳舞","足球","篮球"};
        boolean[] isCheck = new boolean[]{true, false, false, false};
        btn.setOnClickListener(new View.OnClickListener() {
           //点击按钮弹出一个对话框
           @Override
           public void onClick(View v) {
               //1、创建对话框的builder对象
               AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
               //2、该对象用于构建一个对话框模板
               builder.setIcon(R.mipmap.ic_launcher)
                       .setTitle("修改文本大小")
                        .setMultiChoiceItems(showMsg, isCheck, new DialogInterface.OnMultiChoiceClickListener(){
                            @Override
                            //which:选点击哪一项就返回这一项的序号;isChecked:被点击项的选中状态
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                isCheck[which] = isChecked;
                            }
                        })
                       .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               StringBuffer sb = new StringBuffer();
                               for (int i=0; i<isCheck.length; i++){
                                   if (isCheck[i]==true){
                                       sb.append(showMsg[i]).append("    ");
                                   }
                               }
                               Toast.makeText(MainActivity.this, sb, Toast.LENGTH_SHORT).show();
                           }
                       })
                       .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               //关闭当前对话框
                               dialog.dismiss();
                           }
                       });
               //3、builder对象调用create()方法创建一个对话框对象
               AlertDialog alertDialog = builder.create();
               //4、该对象调用show()方法就可以运行了
               alertDialog.show();
           }
        });
    }

    private void initView() {
        btn = findViewById(R.id.btn);

    }
}
<?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=".activitys.MainActivity"
    android:padding="20dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="爱好" />
    </LinearLayout>
</LinearLayout>

ListView

推荐使用RecyclerView

image-20210507170225936 image-20210507170313795 image-20210507170407445 image-20210507170643118 image-20210507170705057 image-20210508193836708

itemlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp">

    <ImageView
        android:layout_width="120dp"
        android:layout_height="90dp"
        android:id="@+id/iv"
        android:layout_centerVertical="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/title"
        android:text="标题"
        android:layout_toRightOf="@+id/iv"
        android:layout_marginBottom="50dp"
        android:layout_marginLeft="10dp"
        android:layout_alignBottom="@+id/iv"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="价格:"
        android:layout_toRightOf="@+id/iv"
        android:layout_marginBottom="15dp"
        android:layout_marginLeft="10dp"
        android:layout_alignBottom="@+id/iv"
        android:textColor="#C5694C"
        android:id="@+id/priceText"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/priceText"
        android:layout_alignBottom="@+id/priceText"
        android:layout_marginLeft="5dp"
        android:text="价格"
        android:textColor="#C5694C"
        android:id="@+id/price"/>

</RelativeLayout>

activity_text_view_1.xml

<?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=".activitys.TextView_1"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="商品列表"
        android:textSize="30dp"
        android:gravity="center"
        android:background="#453737"
        android:textColor="#eee"/>

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

</LinearLayout>

TextView_1.java 未改进过的写法

package com.example.hellp.activitys;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.hellp.R;

public class TextView_1 extends AppCompatActivity {

    ListView myList = null;
    TextView title, price = null;
    ImageView iv = null;

    //1、定义适配器中数组内容
    //图片资源,drawable里面资源都有序列号,所有用int[]
    private int[] icons = {R.drawable.dog, R.drawable.dog2, R.drawable.earth, R.drawable.girl1, R.drawable.girl2, R.drawable.water};

    //标题资源
    private String[] titles = {"小狗", "小狗2", "地球", "美女1","美女2", "水"};

    //价格资源
    private String[] prices = {"10元","20元","30元","40元","50元","60元"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_view_1);
        initView();
    }
    
    private void initView() {
        myList = findViewById(R.id.myList);
        //new一个适配器内部类
        MyAdapter myAdapter = new MyAdapter();
        //给myList添加适配器
        myList.setAdapter(myAdapter);
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {//获取item的数量
            return titles.length;
        }

        @Override
        public Object getItem(int position) {//记录item序号,从0开始
            return titles[position];
        }

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

        @Override
        //用于配置listView要加载的内容,包括视图和数据项
        public View getView(int position, View convertView, ViewGroup parent) {
         
            //1、将item的布局文件解析成view对象,下面操作view的时候相对于在操作itemlayout
            View view = View.inflate(TextView_1.this, R.layout.itemlayout, null);
            //2、找到view中的控件
            title = view.findViewById(R.id.title);
            price = view.findViewById(R.id.price);
            iv = view.findViewById(R.id.iv);
            //3、给控件赋值
            title.setText(titles[position]);
            iv.setBackgroundResource(icons[position]);
            price.setText(prices[position]);
            return view;
        }
    }
}

TextView_1.java 改进过的写法

package com.example.hellp.activitys;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.hellp.R;

public class TextView_1 extends AppCompatActivity {

    ListView myList = null;

    //1、定义适配器中数组内容
    //图片资源,drawable里面资源都有序列号,所有用int[]
    private int[] icons = {R.drawable.dog, R.drawable.dog2, R.drawable.earth, R.drawable.girl1, R.drawable.girl2, R.drawable.water};

    //标题资源
    private String[] titles = {"小狗", "小狗2", "地球", "美女1","美女2", "水"};

    //价格资源
    private String[] prices = {"10元","20元","30元","40元","50元","60元"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_view_1);
        initView();
    }
    private void initView() {
        myList = findViewById(R.id.myList);
        //new一个适配器内部类
        MyAdapter myAdapter = new MyAdapter();
        //给myList添加适配器
        myList.setAdapter(myAdapter);
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {//获取item的数量
            return titles.length;
        }

        @Override
        public Object getItem(int position) {//记录item序号,从0开始
            return titles[position];
        }

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

        @Override
        //用于配置listView要加载的内容,包括视图和数据项
        public View getView(int position, View convertView, ViewGroup parent) {
            //优化写法,需要一个静态类
            ViewHolder holder = null;
            //用于缓存item视图的一个对象,如果为空就把itemlayout转换成View对象
            if (convertView==null){
                convertView = View.inflate(TextView_1.this, R.layout.itemlayout, null);
                holder = new ViewHolder();
                holder.title = convertView.findViewById(R.id.title);
                holder.price = convertView.findViewById(R.id.price);
                holder.iv = convertView.findViewById(R.id.iv);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.iv.setBackgroundResource(icons[position]);
            holder.price.setText(prices[position]);
            holder.title.setText(titles[position]);
            return convertView;
        }
    }

    static class ViewHolder {
        TextView title;
        TextView price;
        ImageView iv;
    }
}

RecyclerView

image-20210508185506114image-20210508185958337

image-20210508193440611

item_layout2.xml

<?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:padding="10dp"
    android:gravity="center_vertical">

    <ImageView
        android:layout_width="120dp"
        android:layout_height="100dp"
        android:id="@+id/iv"/>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/title"
            android:text="标题"
            android:textColor="#BD1919"
            android:background="#E6DBDB"
            android:textSize="30sp"
            android:layout_marginLeft="20dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/info"
            android:text="详细信息"
            android:maxLines="2"
            android:ellipsize="end"
            android:textColor="#fff"
            android:background="#704343"
            android:textSize="30sp"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:layout_below="@+id/title"/>
    </RelativeLayout>

</LinearLayout>

activity_recycler_view_test.xml

<?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=".activitys.RecyclerViewTest"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/myList"/>

</LinearLayout>

RecyclerViewTest.java

package com.example.hellp.activitys;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hellp.R;

public class RecyclerViewTest extends AppCompatActivity {


    /*
    * 1、获取到recyclerView控件对象
    * 2、设计recyclerView控件的适配器,包括item视图的布局和数据内容都要在适配器中定义出来
    * 3、设计recyclerView的布局管理器
    * 4、创建适配器对象,将此对象交付给recyclerView控件对象
    * */

    private RecyclerView myList;
    private int[] icons = {R.drawable.dog, R.drawable.dog2, R.drawable.earth, R.drawable.girl1, R.drawable.girl2, R.drawable.water};
    private String[] titles = {"小狗", "小狗2", "地球", "美女1","美女2", "水"};
    private String[] introduces = {
            "小狗真好看真好看真好看真好看真好看真好看真好看真好看真好看",
            "小狗2真好看真好看真好看真好看真好看真好看真好看真好看真好看",
            "地球真大真大真大真大真大真大真大真大真大真大真大真大真大真大真大",
            "美女1111111111111111111111111111111111111111111111",
            "美女22222222222222222222222222222222222222222222222",
            "水喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝喝"};

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

    private void initView() {
        myList = findViewById(R.id.myList);
        //设置布局的形式是垂直布局
        myList.setLayoutManager(new LinearLayoutManager(RecyclerViewTest.this, LinearLayoutManager.VERTICAL, true));
        MyAdapter myAdapter = new MyAdapter();
        myList.setAdapter(myAdapter);
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder> {

        @NonNull
        @Override
        //获取itemView的视图对象,并将视图对象传递给viewHolder
        public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //将item_layout2布局转换成View对象
            View v1 = View.inflate(RecyclerViewTest.this, R.layout.item_layout2, null);
            MyHolder myHolder = new MyHolder(v1);
            return myHolder;
        }

        @Override
        //将值绑定给holder对象
        public void onBindViewHolder(@NonNull MyHolder holder, int position) {
            holder.info.setText(introduces[position]);
            holder.title.setText(titles[position]);
            holder.iv.setBackgroundResource(icons[position]);
        }

        @Override
        public int getItemCount() {
            return titles.length;
        }

        class MyHolder extends RecyclerView.ViewHolder{
            //定义需要赋值的控件对象
            ImageView iv;
            TextView title, info;
            public MyHolder(@NonNull View itemView) {
                super(itemView);
                iv = itemView.findViewById(R.id.iv);
                title = itemView.findViewById(R.id.title);
                info = itemView.findViewById(R.id.info);
            }
        }
    }
}

自定义View

image-20210508201703117image-20210508201740412

综合练习

image-20210430161255618
package com.example.hellp.activitys;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.hellp.R;

public class myLayout extends AppCompatActivity {

    private EditText et_userName, et_password;
    private Button btn_submit;
    private RadioGroup radioGroup;
    private RadioButton rb1, rb2;
    private String gender;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_layout);
        initView();
        setView();
    }

    private void setView() {
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(myLayout.this,
                        "用户名是:"+et_userName.getText().toString()+"    密码是:"+et_password.getText().toString()+"    你的性别是:"+gender,
                        Toast.LENGTH_SHORT).show();
            }
        });

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            //group接收的就是RadioGroup对象,checkedId接收的是radioButton的id
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId==R.id.rb1){
                    gender = "男";
                }else if (checkedId==R.id.rb2){
                    gender = "女";
                }
            }
        });
    }

    private void initView() {
        et_password = findViewById(R.id.et_password);
        et_userName = findViewById(R.id.et_userName);
        btn_submit = findViewById(R.id.btn_submit);
        radioGroup = findViewById(R.id.radio_group);
        rb1 = findViewById(R.id.rb1);
        rb2 = findViewById(R.id.rb2);
    }
}
<?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=".activitys.myLayout"
    android:orientation="vertical">

   <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="注册"
       android:textSize="30sp"
       android:background="@color/purple_200"
       android:gravity="center"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:layout_gravity="center"
        android:layout_margin="20dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="20dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="用户名:"/>
        <EditText
            android:id="@+id/et_userName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColorHint="@color/purple_200"
            android:hint="请输入用户名"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="20dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密码:"/>
        <EditText
            android:id="@+id/et_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:textColorHint="@color/purple_200"
            android:hint="请输入密码"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="性别:"/>
        <RadioGroup
            android:id="@+id/radio_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <RadioButton
                android:id="@+id/rb1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text=""/>
            <RadioButton
                android:id="@+id/rb2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""/>
        </RadioGroup>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="爱好:"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="羽毛球"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="足球"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="乒乓球"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:gravity="center">
        <Button
            android:id="@+id/btn_submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="提交"
            android:layout_marginRight="20dp"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="取消"/>
    </LinearLayout>
</LinearLayout>

Activity

Activity的生命周期

image-20210508202256884image-20210508202848653

Intent与IntentFilter

image-20210508204049378

在这里插入图片描述
在这里插入图片描述

package com.example.hellp.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import com.example.hellp.R;

public class IntentTestActivity extends AppCompatActivity {

    private Button btn, btn2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_test);
        initView();
        setView();
    }

    private void setView() {
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显式意图
                //点击按钮实现页面的跳转;第一个参数:当前页面;第二个参数:跳转到的页面
                Intent intent = new Intent(IntentTestActivity.this, TextView_1.class);
                //执行意图
                startActivity(intent);
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //隐式意图:根据action属性到清单文件中进行匹配,然后执行匹配上的对应的activity
                Intent intent = new Intent("recyclerViewTest.haha");
                startActivity(intent);
            }
        });
    }

    private void initView() {
        btn = findViewById(R.id.btn);
        btn2 = findViewById(R.id.btn2);
    }
}

image-20210508210428748

Activity之间跳转数据传递

image-20210508212236019
  • 方式一【putExtra】

image-20210508212156787

  • 方式二【bundle】

    传的数据比较琐碎时用bundle封装一下更好。

image-20210508212833012

  • 数据回传

    image-20210508215233284

Activity的任务栈和启动模式

任务栈:一种用来存放Activity实例的容器。

创建Activity时就是将新的Activity入栈,而显示时默认显示栈顶的Activity。

  • 启动模式
image-20210508215707344 image-20210508215754119 image-20210508215856570

使用Fragment

image-20210508220218608 image-20210508220409609

数据存储

文件存储方式

在这里插入图片描述

image-20210509095750166

MainActivity.java

package com.example.hellp;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private Button btnRegister, btnLogin;
    private EditText etUsername, etPwd;

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

        //初始化页面
        initView();
        setView();
    }

    private void setView() {
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //提取输入框中的用户名密码,写入到文件中
                String username = etUsername.getText().toString();
                String password = etPwd.getText().toString();
                if (username.equals("") || password.equals("")){
                    Toast.makeText(MainActivity.this, "用户名、密码不能为空!", Toast.LENGTH_SHORT).show();
                }else if (SaveInfoIO.saveUserInfo(username, password, MainActivity.this)){
                    Toast.makeText(MainActivity.this, "注册成功!", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "注册失败!", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = etUsername.getText().toString();
                String password = etPwd.getText().toString();
                Map<String, String> userInfo = SaveInfoIO.getUserInfo(MainActivity.this);
                Log.d("myLog",password);
                if (userInfo!=null && username.equals(userInfo.get("username")) && password.equals(userInfo.get("password"))){
                    Toast.makeText(MainActivity.this, "登录成功!", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "用户名或密码错误!", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    private void initView() {
        btnLogin = findViewById(R.id.btn_login);
        btnRegister = findViewById(R.id.btn_register);
        etUsername = findViewById(R.id.username);
        etPwd = findViewById(R.id.pwd);
    }
}

SaveInfoIn.java

package com.example.hellp;

import android.content.Context;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SaveInfoIO {
    //用户数据的写入
    public static boolean saveUserInfo(String username, String password, Context context) {
        String msg = null;
        FileOutputStream fos = null;

        try {
            //第一个参数:要操作的文件名;第二个参数:文件的访问方式
            fos = context.openFileOutput("MyData.txt", Context.MODE_PRIVATE);
            msg = username + ":" + password;
            //getBytes()将字符串转换为字节流
            fos.write(msg.getBytes());
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //用户数据的读取
    public static Map<String, String> getUserInfo(Context context){
        //获取文件的输入流
        FileInputStream fis = null;
        try {
            fis = context.openFileInput("MyData.text");
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            String msg = new String(buffer);
            String[] split = msg.split(":");
            HashMap<String, String> map = new HashMap<>();
            map.put("username", split[0]);
            map.put("password", split[1]);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                if (fis!=null){
                    fis.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

activity_main.xml

<?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"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="40dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:layout_marginBottom="20dp"/>
    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名:"/>

    <EditText
        android:id="@+id/pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码:"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_horizontal">
        <Button
            android:id="@+id/btn_register"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="注册"/>

        <Button
            android:id="@+id/btn_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="登录"/>
    </LinearLayout>
</LinearLayout>

SharePreferences方式

此方式比文件方式更便捷

image-20210509100127856

image-20210509101457932

image-20210509101520725

image-20210509101757866

SQLite方式

image-20210509101901122 image-20210509192859777 image-20210509193257676

在这里插入图片描述

在这里插入图片描述

activity_main.xml

<?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"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="20dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:layout_marginBottom="20dp"/>
    <EditText
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名"/>

    <EditText
        android:id="@+id/et_pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"/>

    <Button
        android:id="@+id/btn_select_by_condition"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="条件查询"/>

    <EditText
        android:id="@+id/et_select_by_condition"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入条件"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_horizontal">
        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="增加"/>

        <Button
            android:id="@+id/btn_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="删除"/>

        <Button
            android:id="@+id/btn_update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="修改"/>

        <Button
            android:id="@+id/btn_select"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="查询"/>
    </LinearLayout>

    <TextView
        android:id="@+id/show_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查询显示的结果"
        android:textSize="25sp"/>


</LinearLayout>

MainActivity.java

package com.example.hellp;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_add, btn_delete, btn_update, btn_select, btn_select_by_condition;
    private TextView show_info;
    private MyDbHelper myDbHelper;
    private SQLiteDatabase db;
    private EditText et_username, et_pwd, et_select_by_condition;

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

        initView();
        setView();
    }

    private void setView() {
        btn_add.setOnClickListener(this);
        btn_select.setOnClickListener(this);
        btn_select_by_condition.setOnClickListener(this);
        btn_delete.setOnClickListener(this);
        btn_update.setOnClickListener(this);
    }

    private void initView() {
        btn_add = findViewById(R.id.btn_add);
        btn_delete = findViewById(R.id.btn_delete);
        btn_update = findViewById(R.id.btn_update);
        btn_select = findViewById(R.id.btn_select);
        show_info = findViewById(R.id.show_info);
        et_username = findViewById(R.id.et_username);
        et_pwd = findViewById(R.id.et_pwd);
        btn_select_by_condition = findViewById(R.id.btn_select_by_condition);
        et_select_by_condition = findViewById(R.id.et_select_by_condition);

        //创建数据库和表
        //设置数据库的相关参数,初始化数据库
        myDbHelper = new MyDbHelper(MainActivity.this, "MyDatabase.db", null, 666);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_add:
                //通过帮助类获取到数据库对象
                db = myDbHelper.getWritableDatabase();
                String username = et_username.getText().toString();
                String password = et_pwd.getText().toString();

                //第一种写法
                /*
                //创建一个ContentValues对象,用于存储记录的字段值,以键值对的方式存储,“键”对应字段名
                ContentValues contentValues = new ContentValues();
                //自增的user_id就不用添加了
               // contentValues.put("user_id", 1);
                contentValues.put("userName", username);
                contentValues.put("password", password);
                long i = db.insert("user", null, contentValues);
                if (i!=-1){
                    Toast.makeText(this, "成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(this, "失败", Toast.LENGTH_SHORT).show();
                }
                */
                //第二种写法:?是占位符
                db.execSQL("insert into user (userName, password) values(?, ?)", new Object[]{username, password});
                db.close();
                break;
            case R.id.btn_select:
                db = myDbHelper.getWritableDatabase();
                //Cursor:结果集,结果集中会有游标,游标会指向结果集中的某一条记录,游标指向哪条记录,我们获取的就是哪一条记录,初始时指向第一条记录
                Cursor cursor = db.query("user", new String[]{"userName", "password"}, null, null, null, null, null);
                cursor.moveToFirst();
                show_info.setText("用户名:" + cursor.getString(0) + "   密码:" + cursor.getString(1));
                //移动游标,如果到了最后一条,cursor.moveToNext()返回false
                while (cursor.moveToNext()){
                    show_info.append("\n"+"用户名:" + cursor.getString(0) + "   密码:" + cursor.getString(1));
                }
                cursor.close();
                db.close();
                break;
            case R.id.btn_select_by_condition:
                db = myDbHelper.getWritableDatabase();
                String condition = et_select_by_condition.getText().toString();

                //第一种写法
               // Cursor cursor1 = db.query("user", new String[]{"userName", "password"}, "userName=?", new String[]{condition}, null, null, null);
                //第二种写法
                Cursor cursor1 = db.rawQuery("select userName, password from user where userName=?", new String[]{condition});

                show_info.setText("查询结果如下:");
                while (cursor1.moveToNext()){
                    show_info.append("\n"+"用户名:" + cursor1.getString(0) + "   密码:" + cursor1.getString(1));
                }
                cursor1.close();
                db.close();
                break;
            case R.id.btn_delete:
                db = myDbHelper.getWritableDatabase();
                String condition1 = et_select_by_condition.getText().toString();

                //第一种写法
                /*
                int i = db.delete("user", "userName=?", new String[]{condition1});
                if (i>0){
                    Toast.makeText(this, "删除成功!删除了"+i+"条!", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(this, "删除失败!", Toast.LENGTH_SHORT).show();
                }
                */
                //第二种写法,此方法无法返回删除的条数
                db.execSQL("delete from user where userName=?", new Object[]{condition1});
                db.close();
                break;
            case R.id.btn_update:
                db = myDbHelper.getWritableDatabase();
                String condition2 = et_select_by_condition.getText().toString();
                String username1 = et_username.getText().toString();
                String password1 = et_pwd.getText().toString();
                //第一种写法
                /*
                ContentValues contentValues2 = new ContentValues();
                contentValues2.put("userName", username1);
                contentValues2.put("password", password1);
                db.update("user", contentValues2, "userName=?", new String[]{condition2});
                */
                //第二种写法
                db.execSQL("update user set userName=?, password=? where userName=?", new Object[]{username1, password1, condition2});
                db.close();
                break;
        }
    }

    //数据库帮助类
    class MyDbHelper extends SQLiteOpenHelper {

        //构造器作用:用来定义数据库
        //参数含义:上下文;数据库文件的名称;结果集工厂;版本号
        public MyDbHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        //数据库初始化的时候创建的表,用于创建表或视图文件
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE table user(user_id integer PRIMARY key AUTOINCREMENT, userName varchar(10), password varchar(10))");
        }

        @Override
        //升级方法
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值