Java-Android

Java-Android

  • BasicsTwo
    • 反射
      • 修改方法
      • 修改值
    • 简易IO(面向文件的增删改查)
    • IO流
      • (文件字节输入流)FileInputStream
      • (文件字节输出流) FileOutputStream
      • (文件字符输入流)FileReader
      • (文件字符输出流)FileWriter
      • 【字节流复制(边读边写)】
      • (缓冲输出字符流)BufferedWriter
      • (缓冲输入字符流) BufferedReader
      • (字节字符转换流)
      • (序列化输入流)ObjectInputStream
      • (序列化输出流)ObjectOutputStream
    • 网络编程
      • Server类
      • ServerThread类
      • Client类
      • ClientThread
  • PhaseOne
    • View
    • RadioGroup
    • RadioButton
    • CheckBox
    • Button
    • TextView
    • ImageView
    • ImageButton
    • ScrollView
    • HorizontalScrollView
    • EditText
    • ListView
    • GridView
  • One
    • Menu
      • 系统Menu
      • 上下文Menu
      • 自定义Menu(PopupMenu)
    • 对话框builder
      • 普通对话框
      • 单选对话框
      • 多选对话框
      • 进度条对话框
      • 自定义对话框
      • 自定义弹出窗口(PopupWindow)
    • 通知
      • notification在手机header显示
    • Fragment(UI片段)
      • 创建Fragment
      • 模拟购物界面
        • 布局
        • Fragment类
        • MainActivity类

BasicsTwo

反射

修改方法

public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
     
        ArrayList<String> list = new ArrayList<>();
        list.add("oiuoaisduf");
        list.add("asljkdf");

        Class<? extends ArrayList> aClass1 = list.getClass();       //通过对象名获取class
        Class<ArrayList> aClass2 = ArrayList.class;                 //通过集合获取class
        Class<?> aClass3 = Class.forName("java.util.ArrayList");    //通过包和类名获取class


        Method add = aClass1.getDeclaredMethod("add", Object.class);

        add.invoke(list,5.21345689756);
        add.invoke(list,123456789);
        add.invoke(list,5.21345689756);

        System.out.println(list);

    }

修改值

private static HashMap<String,User> map = new HashMap<>();
    static {
     
        User no1 = new User("wangyide", "5210");
        User no2 = new User("aaa", "123");
        map.put("user1",no1);
        map.put("user2",no2);
    }
    public static void main(String[] args) {
     
        Class<HashMap> hashMapClass = HashMap.class;
        Collection<User> values = map.values();
        Field[] declaredFields = hashMapClass.getDeclaredFields();
    }

简易IO(面向文件的增删改查)

public class Demo {
     
    private static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) throws Exception {
     
        start();
    }

    private static void start() throws Exception {
     
        System.out.println("1.文件目录操作");
        System.out.println("0.退出");
        System.out.println("请输入您的选择:");
        switch (scanner.nextInt())
        {
     
            case 1:
                System.out.println("1:D:\\ 2.C:\\");
                System.out.println("请选择路径");
                File file = new File("D:\\");
                File file1 = new File("C:\\");
                if (scanner.nextInt()==2)
                {
     
                    show(file1);
                }else {
     
                    show(file);
                }
                start();
                break;
            case 0:
                System.out.println("谢谢使用");
                System.exit(0);
                break;
            default:
                System.out.println("输入错误,请重新输入");
                start();
                break;
        }
    }

    private static void show(File file1) throws Exception {
     
        if (file1.isDirectory())
        {
     
            File[] files = file1.listFiles();
            for (File s:
             files) {
     
                System.out.println(s.getName());
            }
            System.out.println("1.继续打开 2.创建文件 3.创建文件夹 4.删除文件或文件夹 5.返回上一级 0.退出");
            int i = scanner.nextInt();
            if (i==1)
            {
     
                System.out.println("请输入文件名:");
                String name = scanner.next();
                for (File s:
                     files) {
     
                    if (name.equals(s.getName()))
                    {
     
                        show(s);
                    }
                }
            }else if (i==2)
            {
     
                System.out.println("请输入文件名(加后缀名如:.txt):");
                String name = scanner.next();
                File file = new File(file1+"/"+name);
                file.createNewFile();
            }else if (i==3)
            {
     
                System.out.println("请输入文件夹名:");
                String name = scanner.next();
                File file = new File(file1+"/"+name);
                file.mkdir();
            }else if (i==4)
            {
     
                System.out.println("请输入要删除的文件夹:");
                String name = scanner.next();
                File file6 = new File(file1+"/"+name);
                deleteFile(file6);
                System.out.println("删除成功");
            }else if (i==0)
            {
     
                System.exit(0);
            }else if (i==5)
            {
     
                String path = file1.getPath();
                File parentFile = file1.getParentFile();
                show(parentFile);
            }
            else {
     
                System.out.println("输入错误");
            }
        }
    }

    private static void deleteFile(File file) {
     
        if (file.exists())
        {
     
            if (file.isFile())
            {
     
                file.delete();
            }else {
     
                if (file.length()==0)
                {
     
                    file.delete();
                }
                File[] files = file.listFiles();
                for (File f:
                     files) {
     
                    if (f.isFile())
                    {
     
                        f.delete();
                    }else {
     
                        deleteFile(f);
                    }
                }
                file.delete();
            }
        }else {
     
            System.out.println("不存在此文件");
        }
    }
}

IO流

缓冲流
缓冲流是用来优化字节或字符流的,
一般字符流比字节流读写要快,但字节流可读取写入除字符以外的数据

序列化流
序列化流可以读取或写入对象,但直接写入会造成乱码

转换流
转换流用来将字节流和字符流相互替换
一般读取JSON-url中的数据获取的流为字节流
一般编程会把字节流转换为字符流
加上缓冲流达到最佳效果

(文件字节输入流)FileInputStream

		FileInputStream fileInputStream = new FileInputStream("字节流.txt");

        byte[] bs = new byte[1024];  //用来存 读到的内容
        int len = fileInputStream.read(bs);  //len:读到的长度

        String string = new String(bs,0,len);
        System.out.println(string);

        fileInputStream.close();

(文件字节输出流) FileOutputStream

		FileOutputStream fileOutputStream = new FileOutputStream("字节流.txt");
        fileOutputStream.write("你好".getBytes());
        fileOutputStream.close();

(文件字符输入流)FileReader

		FileReader fileReader = new FileReader("字符流.txt");
        char[] cs = new char[1024];  //保存读到的内容
        int len = fileReader.read(cs);
        String string = new String(cs,0,len);

        System.out.println(string);
        fileReader.close();

(文件字符输出流)FileWriter

		FileWriter fileWriter = new FileWriter("字符流.txt");
        fileWriter.write("你好");
        fileWriter.close();

【字节流复制(边读边写)】

 //读
        FileInputStream fileInputStream = new FileInputStream("D:\\install\\ideaIU-2020.1.3.exe");
        //写
        FileOutputStream fileOutputStream = new FileOutputStream("D:/aaa.exe");

        byte[] bs = new byte[1024]; //存储读取到的内容

        while (true) {
     
            int len = fileInputStream.read(bs);
            if (len==-1) {
     
                break;
            }
            fileOutputStream.write(bs, 0, len);
        }
        fileInputStream.close();
        fileOutputStream.close();

(缓冲输出字符流)BufferedWriter

		FileWriter fileWriter = new FileWriter("缓冲字符流.txt");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        bufferedWriter.write("缓冲字符流,你好");
        bufferedWriter.close();

(缓冲输入字符流) BufferedReader

		FileReader fileReader = new FileReader("缓冲字符流.txt");
        BufferedReader bufferedReader = new BufferedReader(fileReader);

//		char[] cs = new char[1024];
//
//		int len = bufferedReader.read(cs);
//
//		String string = new String(cs, 0, len);
//		System.out.println(string);

        //特有的方法  读一行
//        String readLine = bufferedReader.readLine();
//        System.out.println(readLine);
		
		//一般使用方法
		String s = "";
		StringBuffer stringbuffer = new StringBuffer();
		while((s = bufferedReader.readLine())!=null){
     
			stringbuffer.append(s);
		}
		
		System.out.println(stringbuffer.toString());
        
        bufferedReader.close();

(字节字符转换流)

		//写
		FileOutputStream fileOutputStream = new FileOutputStream("转换流.txt");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream , "UTF-8");

        outputStreamWriter.write("转换流你好");
        outputStreamWriter.close();
		
		//读
		FileInputStream fileInputStream = new FileInputStream("转换流.txt");

        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");

        char[] cs = new char[1024];
        int len = inputStreamReader.read(cs);
        String string = new String(cs, 0, len);
        System.out.println(string);
        inputStreamReader.close();

(序列化输入流)ObjectInputStream

		FileInputStream fileInputStream = new FileInputStream("序列化流.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

        Student readObject = (Student) objectInputStream.readObject();

        System.out.println(readObject);

        objectInputStream.close();

(序列化输出流)ObjectOutputStream

		FileOutputStream fileOutputStream = new FileOutputStream("序列化流.txt");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        Student student = new Student("张三");

        objectOutputStream.writeObject(student);
        objectOutputStream.close();

网络编程

简单群聊系统

Server类

服务类,用于循环获取客户端的连接,并创建每个连接客户端伴生的服务子线程类

public class Server {
     
    //list用于存储连接中的Socket(存储在线好友)一般用HashMap存储
    //再使用list存储User类
    private static ArrayList<Socket> list = new ArrayList<>();
    
    public static void main(String[] args) throws IOException {
     
        ServerSocket serverSocket = new ServerSocket(37618);
        System.out.println("等待连接中...........");
        int i=0;
        while (true)
        {
     
            Socket accept = serverSocket.accept();
            list.add(accept);
            System.out.println("连接成功");
            new ServerThread(list,accept,i).start();
        }

    }
}

ServerThread类

public class ServerThread extends Thread{
     
    private ArrayList<Socket> arrayList;
    private Socket socket;
    private int i;

    public ServerThread(ArrayList<Socket> arrayList, Socket socket, int i) {
     
        this.arrayList = arrayList;
        this.socket = socket;
        this.i = i;
    }

    @Override
    public void run() {
     
        while (true)
        {
     
            try {
     
                InputStream inputStream = socket.getInputStream();
                byte[] bs = new byte[1024];
                int len = inputStream.read(bs);
                String s = new String(bs, 0, len);
                s=getId()+":"+s;
                for (Socket s1:
                     arrayList) {
     
                    OutputStream outputStream = s1.getOutputStream();
                    outputStream.write(s.getBytes());
                }
            } catch (IOException e) {
     
                e.printStackTrace();
            }

        }
    }
}

Client类

客户端类用来循环提示输入消息,并且发送至服务层

public class Client {
     
    private static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) throws IOException {
     
        Socket socket = new Socket("127.0.0.1",37618);
        new ClientThread(socket).start();           //循环接收消息

        System.out.println("请输入你要群发的消息:");
        while (true)
        {
     
            String next = scanner.next();
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(next.getBytes());
        }
    }
}

ClientThread

客户端子线程类用来循环接收消息,并显示到控制台

public class ClientThread extends Thread{
     
    private Socket socket;

    public ClientThread(Socket socket) {
     
        this.socket = socket;
    }

    @Override
    public void run() {
     
        while (true){
     
            try {
     
                InputStream inputStream = socket.getInputStream();
                byte[] bs = new byte[1024];
                int len = inputStream.read(bs);
                String s = new String(bs, 0, len);
                System.out.println(s);
            } catch (IOException e) {
     
                e.printStackTrace();
            }
        }
    }
}

PhaseOne

View

所有控件的父类,中文翻译为视图

有着基础属性,例如background等

RadioGroup

用于包裹RadioButton的控件

radioButton在选择时,需要实现单选,这是就用到了RadioGroup

Java-Android_第1张图片

RadioButton

单选按钮 一般需要RadioGroup嵌套
android:text=“设置单选按钮后的文字”

style获取Android studio 自带图标
Java-Android_第2张图片
Java-Android_第3张图片

CheckBox

多选框控件,可以不用RadioGroup嵌套,
其余属性和RadioButton类似

Button

继承于TextView
按钮控件 android:text=“用于设置文字”

android:onClick=“设置点击事件方法名” 
写完后(alt+enter)选择create会在java中创建点击事件

TextView

继承于View

按钮控件 android:text=“用于设置文字”,可设置点击事件,
textSize用于设置字体大小,textColor设置颜色等

ImageView

继承于View

显示图片控件,android:src="设置图片位置" 
小技巧:将宽和高其一设置为固定值,另一个设置为wrap_content可防止图片扭曲

ImageButton

继承于ImageView

用法与ImageView类似

ScrollView

可进行垂直滚动的控件,但其中仅可设置一个布局控件,
当内容溢出 即可垂直滑动

HorizontalScrollView

顾名知义,水平滚动控件,简介同上

EditText

继承于TextView

输入文本框控件,android:hint=“可用于设置提示文本”

ListView

可以以列表形式展现的控件,需要设置适配器,或者使用静态item,仅可使用一列

GridView

可以使用多列的ListView

One

Menu

系统Menu

系统menu会在header的右侧显示最小化菜单栏.

必要因素onCreateOptionMenu创建时

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
     
        getMenuInflater().inflate(R.menu.item,menu);
        return super.onCreateOptionsMenu(menu);
    }

必要因素onOptionsItemSelected点击时

@Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
     
        switch (item.getItemId()){
     
            case R.id.option_one:

                break;
            case R.id.option_two:

                break;
            case R.id.option_three:

                break;
        }
        return super.onOptionsItemSelected(item);
    }

上下文Menu

ContextMenu需要绑定控件,并长按绑定空控件显示ContextMenu

必要因素onCreateContextMenu

//加载布局
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
     
        getMenuInflater().inflate(R.menu.menu2, menu);

        super.onCreateContextMenu(menu, v, menuInfo);
    }

必要因素onContextItemSelected

    //监听事件
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
     
        int itemId = item.getItemId();
        switch (itemId) {
     
            case R.id.hong:
                tv1.setTextColor(Color.parseColor("#ff0000"));
                break;
            case R.id.lv:

                break;
            case R.id.lan:

                break;
        }
        return super.onContextItemSelected(item);
    }

自定义Menu(PopupMenu)

对比ContextMenu长按绑定控件显示来说,自定义Menu只需要单击绑定控件即可显示
使用比ContextMenu要灵活
 public void tv1(View view) {
     
        PopupMenu popupMenu = new PopupMenu(this,view);
        popupMenu.inflate(R.menu.menu2);
        popupMenu.show();

        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
     
            @Override
            public boolean onMenuItemClick(MenuItem item) {
     
                int itemId = item.getItemId();
                switch (itemId) {
     
                    case R.id.hong:
                        tv2.setTextColor(Color.parseColor("#ff0000"));
                        break;
                    case R.id.lv:
                        tv2.setTextColor(Color.parseColor("#00ff00"));

                        break;
                    case R.id.lan:
                        tv2.setTextColor(Color.parseColor("#0000ff"));

                        break;
                }
                
                return false;
            }
        });
    }

对话框builder

弹出对话框

普通对话框

普通对话框可以编写Message,编写icon(图标),编写title等
/**
     * 普通对话框
     * @param view
     */
    public void btn1(View view) {
     
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setIcon(R.drawable.icon);
        builder.setTitle("删除");
        builder.setMessage("您确定要删除此消息");
        
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
     
            @Override
            public void onClick(DialogInterface dialog, int which) {
     
                Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show();
            }
        });
        
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
     
            @Override
            public void onClick(DialogInterface dialog, int which) {
     
                Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

单选对话框

顾名知义,单选对话框就是有着radio控件的对话框
/**
     * 单选对话框
     * @param view
     */
    public void btn2(View view) {
     
        final int[] click = new int[1];
        final String[] data = new String[]{
     "足球","篮球","唱歌","台球"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.icon);
        builder.setTitle("单选");

        builder.setSingleChoiceItems(data, 0, new DialogInterface.OnClickListener() {
     
            @Override
            public void onClick(DialogInterface dialog, int which) {
     
                click[0] = which;
            }
        });

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
     
            @Override
            public void onClick(DialogInterface dialog, int which) {
     
                Toast.makeText(MainActivity.this, data[click[0]].toString(), Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
     
            @Override
            public void onClick(DialogInterface dialog, int which) {
     

            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

多选对话框

顾名思义
 //多选对话框
    public void tion3(View view) {
     
        //构建者
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //设置属性
        builder.setIcon(R.drawable.ic_launcher_background);
        builder.setTitle("她们");
        final String[] strings = {
     "小晓", "小齐", "小琳", "晓丽"};
        boolean[] booleans = {
     true,true,false,false};
        //参数  Sing数组  boolean数组 监听事件
        builder.setMultiChoiceItems(strings, booleans, new DialogInterface.OnMultiChoiceClickListener() {
     //多选内容
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
     

            }
        });



        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
     
            @Override
            public void onClick(DialogInterface dialog, int which) {
     
                Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
     
            @Override
            public void onClick(DialogInterface dialog, int which) {
     
                Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
            }
        });
        //创建
        AlertDialog alertDialog = builder.create();
        //显示
        alertDialog.show();
    }

进度条对话框

进度条对话框显示进度 一般用于加载数据中使用
/**
     * 进度条对话框
     * @param view
     */
    public void btn3(View view) {
     
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMax(100);
        progressDialog.setTitle("进度条对话框");
        progressDialog.setIcon(R.drawable.icon);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();
		
		//Timer用于加载进度条 类似于一种循环
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
     
            int i = 0;
            @Override
            public void run() {
     
                if (i==progressDialog.getMax()){
     
                    timer.cancel();
                    progressDialog.dismiss();
                }
                progressDialog.setProgress(i+=1);
            }
        },0,50);

    }

自定义对话框

自定义对话框类似于普通builder,只不过将原先的setMessage改为setView
/**
     * 自定义对话框
     * @param view
     */
    public void btn4(View view) {
     
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("自定义对话框");
        builder.setIcon(R.drawable.icon);
        View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.menu, null);
        builder.setView(inflate);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();

        inflate.findViewById(R.id.btn_yes).setOnClickListener(new View.OnClickListener() {
     
            @Override
            public void onClick(View v) {
     
                Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show();
                alertDialog.dismiss();
            }
        });

        inflate.findViewById(R.id.btn_no).setOnClickListener(new View.OnClickListener() {
     
            @Override
            public void onClick(View v) {
     
                Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
                alertDialog.dismiss();
            }
        });
    }

自定义弹出窗口(PopupWindow)

PopupWindow使用比PopupMenu更加灵活,可以设置弹出位置
public void btn1(View view) {
     
        PopupWindow popupWindow = new PopupWindow();
        //宽高必须要有
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        //点击外部取消
        popupWindow.setOutsideTouchable(true);

        //遮罩效果
        //WindowManager.LayoutParams attributes = getWindow().getAttributes();
        //attributes.alpha = 0.5f;
        //getWindow().setAttributes(attributes);

        //恢复透明度
        //popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
     
        //    @Override
        //    public void onDismiss() {
     
        //        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        //        attributes.alpha = 1.0f;
        //        getWindow().setAttributes(attributes);
        //    }
        //});


        //加载布局
        View inflate = LayoutInflater.from(this).inflate(R.layout.popu, null);
		//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        popupWindow.setContentView(inflate);//设置布局

        View activity_main = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        //在activity_main布局的最下边
        popupWindow.showAtLocation(activity_main, Gravity.BOTTOM,0,0);

        //显示到某个控件的下边
        //popupWindow.showAsDropDown(add);

        //设置入场动画
        //popupWindow.setAnimationStyle(R.style.popuoo);

        //控件里的点击事件
        inflate.findViewById(R.id.sao).setOnClickListener(new View.OnClickListener() {
     
            @Override
            public void onClick(View v) {
     
                Toast.makeText(MainActivity.this, "hhhhhhh", Toast.LENGTH_SHORT).show();
            }
        });

    }

简化版

public void btn1(View view) {
     
        PopupMenu popupMenu = new PopupMenu(this,view);
        
        PopupWindow popupWindow = new PopupWindow();

        popupWindow.setWidth(300);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        popupWindow.setOutsideTouchable(true);

        View inflate1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.menu, null);
        popupWindow.setContentView(inflate1);

        View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
//        popupWindow.showAtLocation(inflate, Gravity.RIGHT,0,-500);
        RelativeLayout relativeLayout = findViewById(R.id.title);
        popupWindow.showAsDropDown(relativeLayout,9999,0);


    }

通知

notification在手机header显示

public void btn1(View view) {
     
        //构造者
        Notification.Builder builder = new Notification.Builder(this);

        //小图标(必须设置,不然报错)
        builder.setSmallIcon(R.drawable.ic_launcher_background);

        //加载布局
        RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.notification);
        
		//设置文字
		//remoteViews.setTextViewText(R.id.text_id,"设置文字");
        //设置图片
		//remoteViews.setImageViewResource(R.id.img_id,R.drawable.ic_launcher_background);	
		
        //设置自定义布局
        builder.setCustomContentView(remoteViews);
        // Big
        //builder.setCustomBigContentView(remoteViews);

        //发通知
        NotificationManager systemService = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        systemService.notify(1,builder.build());

    }

Fragment(UI片段)

fragment配合RadioGroup和RadioButton可以实现 购物软件下方导航

创建Fragment

Java-Android_第4张图片

模拟购物界面

布局

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".BlankFragment1">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="111111111111111111111111111111"/>
</FrameLayout>

Fragment类

public class BlankFragment1 extends Fragment {
     


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
     
        // Inflate the layout for this fragment
        
        return inflater.inflate(R.layout.fragment_blank_fragment1, container, false);
    }

}

MainActivity类

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
     
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
     
                //利用switch来切换不同的UI片段
                switch (checkedId){
     
                    case R.id.index:
                        //管理者对象(片段管理器)
                        FragmentManager manager = getSupportFragmentManager();

                        //开启事务
                        FragmentTransaction fragmentTransaction = manager.beginTransaction();

                        //添加fragment
                        Index index = new Index();
						
						//替换片段
						//其中R.id.ll是Main布局中的片段容器,
						//index是Fragment
						//另外add是添加,replace是替换
						//fragmentTransaction.add(R.id.ll,index);
                        fragmentTransaction.replace(R.id.ll, index);
						//提交事务
                        fragmentTransaction.commit();
                        break;
                     
                }
            }
        });

你可能感兴趣的:(Java-Android)