幻樱の安卓开发学习笔记(持续更新)

安卓开发手册Java

.
前言
.
本篇博客是我在开发过程中遇到的一些问题,我将这些问题记录了下来,以防踩重复的坑,希望对需要学习或者来看我踩坑的人有所帮助。
.

.

.
.

零、一些常用的依赖

1.Volley

implementation 'com.android.volley:volley:1.1.1'  

网站链接:https://developer.android.com/training/volley/simple

基本使用方法:

 RequestQueue queue = Volley.newRequestQueue(this);
    String url ="http://www.google.com";
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
   
    
    
        @Override
        public void onResponse(String response) {
   
    
    
            //这里写事件  
            //response是解析的值,多是json
        }
    }, new Response.ErrorListener() {
   
    
    
        @Override
        public void onErrorResponse(VolleyError error) {
   
    
    
         
        }
    });

    queue.add(stringRequest);

2.Gson

   implementation 'com.google.code.gson:gson:2.8.6'

序列化和反序列化

链接:https://github.com/google/gson

手册:https://github.com/google/gson/blob/master/UserGuide.md

基本使用:

Gson gson = new Gson();//实例化

gson.toJson(这里传入对象)//对象转化json
gson.fromJson(json (这个是json字符串,string类型), fooType (这是bean对象,基本上传入的是 xxxbean.class)); //json转换对象

//复杂类型转换对象
Type fooType = new TypeToken<Foo<Bar>>() {
   
    
    }.getType();//需要先处理一下,用法与上面一样
gson.toJson(foo, fooType);
gson.fromJson(json, fooType);

3.Glide

 implementation 'com.github.bumptech.glide:glide:4.11.0'
 annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'

手册:https://muyangmin.github.io/glide-docs-cn/doc/getting-started.html

基本使用:

//加载
Glide.with(fragment)
    .load(myUrl)
    .into(imageView);

//取消加载同样很简单:
Glide.with(fragment).clear(imageView);

4.Aria

implementation 'com.arialyy.aria:core:3.8.10'
annotationProcessor 'com.arialyy.aria:compiler:3.8.10'
implementation 'com.arialyy.aria:ftpComponent:3.8.10' # 如果需要使用ftp,请增加该组件
implementation 'com.arialyy.aria:sftpComponent:3.8.10' # 如果需要使用ftp,请增加该组件
implementation 'com.arialyy.aria:m3u8Component:3.8.10' # 如果需要使用m3u8下载功能,请增加该组件

手册:https://github.com/AriaLyy/Aria

使用

由于Aria涉及到文件和网络的操作,因此需要你在manifest文件中添加以下权限,如果你希望在6.0以上的系统中使用Aria,那么你需要动态向安卓系统申请文件系统读写权限,如何使用安卓系统权限

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

基本使用

例子为单任务下载,只需要很简单的代码,便可以实现下载功能。

  • 创建任务

    long taskId = Aria.download(this)
        .load(DOWNLOAD_URL)     //读取下载地址
        .setFilePath(DOWNLOAD_PATH) 
        //设置文件保存的完整路径  这里的目录必须包含 文件名.后缀
        // 例: String sd = Environment.getExternalStorageDirectory().getPath() + "/幻樱";
        // String randomString = sd + "/" + getRandomString(10随机生成字符) + ".jpg";
        .create();   //创建并启动下载
    
  • 停止\恢复任务

    Aria.download(this)
        .load(taskId)     //读取任务id
        .stop();       // 停止任务
        //.resume();    // 恢复任务
    

5.PhotoView

图片手势缩放

链接:https://github.com/chrisbanes/PhotoView

dependencies {
   
    
    
    implementation 'com.github.chrisbanes:PhotoView:latest.release.here'//当前最新版本 可能会下载报错
        
    implementation 'com.github.chrisbanes.photoview:library:1.2.4'//这个历史版本稳定
}

使用方式:

布局

<com.github.chrisbanes.photoview.PhotoView
    android:id="@+id/photo_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

java

PhotoView photoView = (PhotoView) findViewById(R.id.photo_view);
photoView.setImageResource(R.drawable.image);

.
.
.

一、常用控件的基本使用

1.下拉刷新

需要在布局里面添加 swiperefreshlayout 控件

在子集里面添加列表布局

 <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

事件基本使用写法

 swipeRefreshLayout.setColorSchemeResources(R.color.colorTheme,R.color.colorPrimaryDark,R.color.colorAccent);//设置加载小圈圈的颜色,多写几种颜色在加载的时候会变色,默认一种就够了
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
   
    
    //监听事件
            @Override
            public void onRefresh() {
   
    
    
                //这里处理加载时的事件
                Toast.makeText(getContext(), "正在加载...", Toast.LENGTH_SHORT).show();
          
                new Handler().postDelayed(new Runnable() {
   
    
    //新建一个线程
                    @Override
                    public void run() {
   
    
    
                        //后台继续加载
                       // Toast.makeText(getContext(), "加载完成", Toast.LENGTH_SHORT).show();
                        Snackbar.make(getView(),"加载完成", BaseTransientBottomBar.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);//加载完后隐藏小圈圈
                    }
                }, 2500);//下拉小圈圈出现到隐藏的时间
            }
        });

2.RecyclerView

列表倒序排列

staggeredGridLayoutManager.setReverseLayout(true);//列表翻转

焦点定位到最后一位

 LinearLayoutManager manager = new LinearLayoutManager(getContext());
 manager.setStackFromEnd(true);  //焦点显示到最后一位

位置定位到最后一位

rv.smoothScrollToPosition(Adapter.getItemCount() - 1);  //这条要加在添加数据后面,不然会崩溃

3.DrawerLayout

DrawerLayout是一个根布局,最多可以放三个子布局

侧拉栏的布局基本使用

//main根目录改为drawerLayout
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:openDrawer="start">  //是否在布局界面预览

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NqTi720m-1608111188416)(C:\Users\sakura\AppData\Roaming\Typora\typora-user-images\image-20200826111640820.png)]

左边蓝线就是Navigation的布局(布局预览未开)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lEWQ1F6T-1608111188419)(C:\Users\sakura\AppData\Roaming\Typora\typora-user-images\image-20200826111829645.png)]

代码: tools:openDrawer=“start” 预览开启的样子 ,遮挡了后面的主页

4.NavigationView

Navigation配合DrawerLayout可以实现侧拉栏效果

侧拉栏内容的布局

<com.google.android.material.navigation.NavigationView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"   //从左边拉出来, end是从右边拉出来
        app:headerLayout="@layout/navigationview_head_layout" //头部(顶栏)部分的布局
        app:menu="@menu/navigationview_menu" />  //添加菜单布局

基本布局代码整体:

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:openDrawer="start">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="主页"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.navigation.NavigationView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/navigationview_menu" />

</androidx.drawerlayout.widget.DrawerLayout>

5.BottomNavigation

底部导航栏的基本使用

准备工作:创建一个menu文件,创建几个fragment(这是切换的布局)

1.创建一个导航文件

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zB0QYn68-1608111188421)(C:\Users\sakura\AppData\Roaming\Typora\typora-user-images\image-20200826153721386.png)]

2.导航里面添加创建的fragment布局 (注意ID名,菜单的 item 的 Id 要和这个一样,不然不能导航 )

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XOb7xjad-1608111188424)(C:\Users\sakura\AppData\Roaming\Typora\typora-user-images\image-20200826153825989.png)]

3.xml布局

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemIconTint="@color/colorAccent"
        app:itemTextColor="@color/colorAccent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottomnavigation_menu" />

    <fragment
        android:id="@+id/fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#6A303B"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/navigtion_switch_fragment" />
</androidx.constraintlayout.widget.ConstraintLayout>

4.写java代码把底部菜单和fragment绑定起来

//绑定控件
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
//绑定fragment控件
NavController navController = Navigation.findNavController(this, R.id.fragment);
//绑定3个fragment布局
AppBarConfiguration configuration = new AppBarConfiguration.Builder(R.id.homeFragment, R.id.otherFragment, R.id.downloadFragment).build();
//映射到UI
NavigationUI.setupActionBarWithNavController(this, navController, configuration); //如果隐藏了标题栏就不设置这个
NavigationUI.setupWithNavController(bottomNavigationView, navController);
//设置导航栏背景颜色为透明
bottomNavigationView.setBackgroundResource(android.R.color.transparent);

//不被颜色影响 , 只要将这个属性设置为 null ,图标原本是什么颜色,那么显示就是什么颜色, xml 里面没效果,要运行后才生效
bottomNavigationView.setItemIconTintList(null);

.
.
.

二、Adapter的基本使用

1.RecyclerViewAdapter

public class BannerAdapter extends RecyclerView.Adapter<BannerAdapter.ViewHolder> {
   
    
    
    Context context; //上下文
    List<String> list;  //列表可以是其他类型

    public BannerAdapter(Context context, List<String> list) {
   
    
     //构造方法
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public BannerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
   
    
    
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.banner_item_layout, parent, false));
        //返回设置的列表布局
    }

    @Override
    public void onBindViewHolder(@NonNull BannerAdapter.ViewHolder holder, int position) {
   
    
    

        Glide.with(context)
                .load(list.get(position))
                .into(holder.imageView);
        
        //使用Glide加载图片
    }

    @Override
    public int getItemCount() {
   
    
    
//返回list数
        if (list.size() == 0) {
   
    
    
            return 0;
        }
        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
   
    
    
        ImageView imageView;

        public ViewHolder(@NonNull View itemView) {
   
    
    
            super(itemView);
            imageView = itemView.findViewById(R.id.banner_item_img);
            //viewHolder控件绑定
            
            //这里也可以写列表点击事件
             itemView.setOnClickListener(new View.OnClickListener() {
   
    
    
                @Override
                public void onClick(View view) {
   
    
    
                    //这里写点击事件
                }
            });
        }
    }
}

2.在ViewHolder中使用Intent

public ViewHolder(@NonNull View itemView) {
   
    
    
    super(itemView);
    itemView.setOnClickListener(new View.OnClickListener() {
   
    
    
        @Override
        public void onClick(View view) {
   
    
    //从点击列表跳转到指定activity
            Intent intent = new Intent(context, PhotoViewActivity.class);
                                     //动态获取当前点击的列表的position
            intent.putExtra("url", gList.get(getAdapterPosition()).getUrl());
            //用context来跳转
            context.startActivity(intent);
        }
    });
}

3.瀑布流检测是否到底部

//检测瀑布流是否到底部
StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
int arr[] = new int[2];
int[] lastItem = manager.findLastCompletelyVisibleItemPositions(arr); // 获取最后一个item
int lastPos = getMaxElem(lastItem);//调用方法把数组转换为int
int itemCount = manager.getItemCount(); //获取当前全部item
switch (newState) {
   
    
    
    case RecyclerView.SCROLL_STATE_IDLE: // 当前列表没有滑动.
        //当屏幕停止滚动,加载图片
        try {
   
    
    
            if (lastPos == itemCount - 1) {
   
    
    
                homeVolley.getHomeVolley(); //调用数据解析
                if (this != null) Glide.with(getActivity()).resumeRequests();
            }
        } catch (Exception e) {
   
    
    
            e.printStackTrace();
        }
        break;

    case RecyclerView.SCROLL_STATE_DRAGGING:
        //当屏幕滚动且用户使用的触碰或手指还在屏幕上,停止加载图片
        try {
   
    
    
            if (this != null) Glide.with(getActivity()).pauseRequests();
        } catch (Exception e) {
   
    
    
            e.printStackTrace();
        }
        break;

    case RecyclerView.SCROLL_STATE_SETTLING: 
        //由于用户的操作,屏幕产生惯性滑动,停止加载图片
        try {
   
    
    
            if (this != null) Glide.with(getActivity()).pauseRequests();
        } catch (Exception e) {
   
    
    
            e.printStackTrace();
        }
        break;
}






//把数组转换为int
 private int getMaxElem(int[] arr) {
   
    
    
        int size = arr.length;
        int maxVal = Integer.MIN_VALUE;
        for (int i = 0; i < size; i++) {
   
    
    
            if (arr[i] > maxVal)
                maxVal = arr[i];
        }
        return maxVal;
    }

.
.
.

三、经常遇到的问题

1.动态设置图片控件宽高度

可以解决在图片还未加载完成时的布局错乱问题

ViewGroup.LayoutParams layoutParams = holder.imageView.getLayoutParams();  //把获取的控件高度传入到 layoutParams
int height = gList.get(position).getHeight(); //从列表里面读取解析过来的图片宽高
layoutParams.height = height;  //把宽高设置为获取的宽高
holder.imageView.setLayoutParams(layoutParams); //设置控件的宽高为获取到的宽高

2.侧拉栏状态栏不透明问题

<com.google.android.material.navigation.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer"
    //加这一行代码即可解决                                                   
    app:insetForeground="@android:color/transparent"/>

3.动态获取权限

private void getPermissions() {
   
    
    
    /**
     * 如果安卓版本小于29且没有读写权限,那么就申请权限
     */
    if (Build.VERSION.SDK_INT < 29 && ContextCompat.checkSelfPermission(
            getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
            PackageManager.PERMISSION_GRANTED) {
   
    
    
        requestPermissions(new String[]{
   
    
    Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    } else {
   
    
    
        //如果有权限那就直接执行以下代码
        Toast.makeText(this, "点击了保存", Toast.LENGTH_SHORT).show();
    }


}

参考链接:https://developer.android.com/training/permissions/requesting?hl=zh-cn#java

4.在外置内存创建文件夹

private void isDirectoryFile() {
   
    
    
    /**
     * 如果没有当前文件夹就创建
     */
    //       这里获取的是外置内存根目录 /storage/sdcard0/     +   自定义文件夹名
    String sd = Environment.getExternalStorageDirectory().getPath() + "/幻樱";    //获取目录也是这个写法
    File dirFile = new File(sd); 
    if (!dirFile.exists()) {
   
    
    
        boolean mkdirs = dirFile.mkdirs();//创建文件夹
        Log.d("test", "文件夹创建成功");
    } else {
   
    
    
        Log.d("test", "文件夹已经存在");
    }


}

5.随机数生成

//生成随机数
Random random = new Random();
int i = random.nextInt(4); //范围0-4
//生成字符串
public static String getRandomString(int length) {
   
    
      //传入需要的字符长度
    String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    Random random = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < length; i++) {
   
    
    
        int number = random.nextInt(62);//总共62个
        sb.append(str.charAt(number)); //遍历的字符随机组合
    }
    return sb.toString();   //返回字符串
}

6.壁纸选择器

Intent intent = new Intent(ACTION_SET_WALLPAPER);
startActivity(intent);

7.隐藏状态栏

getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//隐藏状态栏

或者在style文件里面配置

<item name="android:windowFullscreen">true</item>

8.创建导航栏菜单

/**
 * 导航栏右边菜单
 *
 * @return
 */
@Override    //重写 onCreateOptionsMenu 方法
public boolean onCreateOptionsMenu(Menu menu) {
   
    
    
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

9.获取菜单列表点击事件

/**
 * 菜单列表点击事件
 *
 * @param item
 * @return
 */
@Override             //重写 onOptionsItemSelected 方法
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
   
    
    

    switch (item.getItemId()) {
   
    
    
        case R.id.菜单列表ID:
            Toast.makeText(this, "这是" + item.toString(), Toast.LENGTH_SHORT).show();
            break;
        case R.id.菜单列表ID:

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

10.自定义弹窗宽度

//代码要写在show方法后面,不然不生效
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.width = (int)(display.getWidth() * 0.9); //设置宽度
dialog.getWindow().setAttributes(lp);

11.SharedPreferences使用

//                           文件是以xml存储的              存储类型
SharedPreferences sp = getSharedPreferences("文件名",Context.Context.MODE_PRIVATE)
//编辑器
SharedPreferences.Editor editor = sp.edit();
//添加为 string int Boolean 等类型
editor.putxxx("key",v);
//完成提交
editor.commit();


//读取
//什么类型写入就读什么类型  key与上面传入的一样  如果读不到就返回 Null
sp.getxxx("key",Null);


12.透明状态栏

具体用法需要配合 fitsSystemWindows 为 true 时

image-20200826182136909
//添加到color.xml里面,然后把style.xml里面的 colorPrimaryDark 颜色替换就行了
<color name="alphaColor">@android:color/transparent</color>

13.禁止屏幕旋转

在Manifest文件的 .MainActivity里面添加

android:screenOrientation="portrait"

14.允许明文访问

也就是Http访问

在Manifest文件的 application下添加

//模拟器内置浏览器报错 
net::ERR_CLEARTEXT_NOT_PERMITTED

在配置文件 Manifest 中的 application 里面添加

android:usesCleartextTraffic="true"

15.include引用布局的点击事件

1.首先得创建一个布局,布局内的控件定义好ID,在其他XML布局里面用标签引用

2.在java里面调用引用布局里面的控件,达到动态引用的作用(一个布局被多个布局调用,并且能改里面的具体内容)

3案例:

APP 的 Title ,左边一个返回,中间一个文本

<?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"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/title_include_back"
        android:layout_width="60dp"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_gravity="center"
            android:layout_marginLeft="20dp"
            app:srcCompat="@drawable/back" />
    </LinearLayout>

    <TextView
        android:id="@+id/title_inculde_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity

猜你喜欢

转载自blog.csdn.net/Sakura_huatex/article/details/109013760