目录安卓开发常见布局常用控件TextViewButtonImageViewEditViewToastCheckBoxListViewRecyclerView自定义View综合练习ActivityActivity的生命周期Intent与IntentFilterActivity之间跳转数据传递Activity的任务栈和启动模式使用Fragment数据存储文件存储方式SharePreferences方式SQLite方式常见布局线性布局安卓学习笔记。对应b站视频
linearLayout
如果使用了权重,通常设元素宽度为0,否则会冲突以wIDth为主。
相对布局relativeLayout
表格布局 tableLayout
帧布局 FrameLayout
常用控件TextVIEwbutton 点击事件写法Ⅰ
通过按钮的onClick指定点击事件出发的方法,方法在对应的activity中实现。
点击事件写法Ⅱ
通过匿名内部类的方式是实现。
ImageVIEwEditVIEwToastCheckBoxpackage 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对话框带【确定】【取消】按钮的对话框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() { //点击按钮d出一个对话框 @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>
带【单选】的对话框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() { //点击按钮d出一个对话框 @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>
带【多选】的对话框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() { //点击按钮d出一个对话框 @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
@H_745_301@
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@H_419_375@
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综合练习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>
ActivityActivity的生命周期Intent与IntentFilterpackage 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); }}
Activity之间跳转数据传递方式一【putExtra】 方式二【bundle】
传的数据比较琐碎时用bundle封装一下更好。
数据回传
Activity的任务栈和启动模式任务栈:一种用来存放Activity实例的容器。
创建Activity时就是将新的Activity入栈,而显示时默认显示栈顶的Activity。
启动模式使用Fragment数据存储文件存储方式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方式此方式比文件方式更便捷
sqlite方式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条)