直接放代码
查阅资料后自己总结的 BaseShareView
abstract class BaseShareView(context: Context) : FrameLayout(context) { /** * 等价于:context.resources.displayMetrics.widthPixels */ private val IMAGE_WIDTH = XDensityUtils.getScreenWidth() /** * 等价于:context.resources.displayMetrics.heightPixels */ private val IMAGE_HEIGHT = XDensityUtils.getScreenHeight() /** * 绘制要分享的Bitmap */ private fun createBitmap(): Bitmap? { val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) //使用Canvas,调用自定义view控件的onDraw方法,绘制图片 draw(Canvas(bitmap)) return bitmap } /** * 实际使用时必须要调用该方法,但是真正有分享功能的是有参数的那个share */ fun share() { LayoutInflater.from(context).inflate(getLayoutId(), this) initViewExcludeImageView() measure( MeasureSpec.makeMeasureSpec(IMAGE_WIDTH, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(IMAGE_HEIGHT, MeasureSpec.EXACTLY) ) layout(0, 0, measuredWidth, measuredHeight) initImageView() } /** * 测量完成后才能使用Glide加载图片,否则Glide不知道图片大小,显示不出来 */ abstract fun initImageView() /** * 自定义layout的id */ abstract fun getLayoutId(): Int /** * 初始化除了ImageView之外的view,必须在测量前,否则可能显示不出来 */ abstract fun initViewExcludeImageView() /** * 真正的share,无参数的那个[share]可能会进行耗时操作,因此需要手动调用此方法,实际使用的时候还是调用的那个无参数的[share] */ fun share(shareTitle: String?, description: String?) { val pictureBitmap = createBitmap() if (pictureBitmap == null) { XToast.error(context.getString(R.string.share_failed)) } else { context.startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).apply { type = "image/*" addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) putExtra( Intent.EXTRA_STREAM, Uri.parse( MediaStore.Images.Media.insertImage( context.contentResolver, pictureBitmap, shareTitle, description ?: context.getString(R.string.empty_description) ) ) ) }, shareTitle)) } } }
如何使用
class ExampleShareView(context: Context) : BaseShareView(context) { override fun initImageView() { //初始化imageview,然后调用有参数的share方法 ...... share("标题","描述") } override fun getLayoutId(): Int { //返回自定义分享布局 return R.layout.xxx } override fun initViewExcludeImageView() { //初始化非ImageView,比如TextView等 ... } companion object{ /** * 如何调用 */ @JvmStatic fun main(args: Array<String>) { //传入context,一定要记得调用share()方法 ExampleShareView(context).share() } } }
[========]