Android 仿知乎分享控件

Android 仿知乎分享控件

使用 BottomSheetDialog 实现仿知乎分享控件
主要步骤:java

  1. 首先获取手机内全部支持分享的应用,获得 ResolveInfo 对象,利用反射获取应用图标等信息
  2. 而后用 RecyclerView 的 GridLayoutManager 网格布局展现,本身实现点击事件就差很少完成了

截图

知乎
知乎
仿
仿
原生
原生
知乎 仿 原生

简单实现

  • 写一个分享界面的布局android

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
    
        <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:text="我是广告栏" android:textAppearance="@style/TextAppearance.AppCompat" android:textSize="18sp"/>
    
        <View android:layout_width="match_parent" android:layout_height="1px" android:background="@android:color/darker_gray"/>
    
        <android.support.v7.widget.RecyclerView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent"/>
    
    </LinearLayout>复制代码
  • 在 Activity 里使用 BottomSheetDialog 控件显示git

    BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this);
    mBottomSheetDialog.setContentView(R.layout.dialog_bottom_sheet);
    mBottomSheetDialog.show();复制代码
  • 写一个 RecyclerViewAdapter 和 appinfo_item 布局github

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical">
    
        <ImageView
            android:id="@+id/img_list_item"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:scaleType="centerCrop"
            tools:src="@mipmap/ic_launcher"/>
    
        <TextView
            android:id="@+id/text_list_item"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:ellipsize="end"
            android:singleLine="true"
            tools:text="分享11111111111111"/>
    </LinearLayout>复制代码
  • 获取手机内全部支持分享的应用列表bash

    public static List<ResolveInfo> getShareApps(Context context, Intent intent) {
            List<ResolveInfo> resolveInfoList;
            PackageManager pm = context.getPackageManager();
            resolveInfoList = pm.queryIntentActivities(intent, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
            return resolveInfoList;
        }复制代码
  • 返回数据给 Activity,而后设置 Adapter 就差很少完成,详细代码见 ZhihuShareDialogapp

缺点

  • 经过 PackageManager 的 queryIntentActivities 方法获取到的应用是按照应用安装的前后顺序,而 Lollipop(5.0) 开始原生分享已支持自动把经常使用应用排在最顶部。固然也能够本身实现应用的排序,但比较折腾,可参考源码 ResolverActivity布局

优势

  • 能够自定义分享界面,好比像知乎那样添加广告栏,设计一套属于本身的 UI ,设置应用的排列顺序等等

源码下载地址 : github.com/iMeiji/Zhih…this

相关文章
相关标签/搜索