Android 仿知乎分享控件

4,614 阅读1分钟

Android 仿知乎分享控件

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

  1. 首先获取手机内所有支持分享的应用,得到 ResolveInfo 对象,利用反射获取应用图标等信息
  2. 然后用 RecyclerView 的 GridLayoutManager 网格布局展示,自己实现点击事件就差不多完成了

截图

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

简单实现

  • 写一个分享界面的布局

    <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 控件显示

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

    <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>
  • 获取手机内所有支持分享的应用列表

    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 就差不多完成,详细代码见 ZhihuShareDialog

缺点

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

优点

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

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