废话不多说,源码直接奉上,调用的是android自带的分享,不需要弄一大堆第三方
下面是XMl代码。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/tv_fen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp"
android:background="#ffffff">
<Button
android:id="@+id/btn_fen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="17sp"
android:textColor="@color/black"
android:text="分享"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="分享分享分享"
android:textColor="@color/black"
android:textSize="17sp"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
下面是Activity代码。
public class fen_xiang extends AppCompatActivity implements View.OnClickListener{
private Button btn_fen;
private LinearLayout tv_fen;
@Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fenxian);
btn_fen = (Button) findViewById(R.id.btn_fen);
tv_fen = (LinearLayout) findViewById(R.id.tv_fen);
tv_fen.setDrawingCacheEnabled(true);
btn_fen.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_fen) {
Bitmap bitmap = tv_fen.getDrawingCache();
mHandler.postDelayed(mResetCache, 200);
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
// 比如发送图片形式的数据内容
// 指定发送的内容
sendIntent.putExtra(Intent.EXTRA_STREAM, saveBitmap(bitmap,"内容"));
// 指定发送内容的类型
sendIntent.setType("image/*");
startActivity(Intent.createChooser(sendIntent, "分享到... ..."));
}
}
/** * 将图片存到本地 */
private static Uri saveBitmap(Bitmap bm, String picName) {
try {
String dir= Environment.getExternalStorageDirectory().getAbsolutePath()+"/fenxiang/"+picName+".jpg";
File f = new File(dir);
if (!f.exists()) {
f.getParentFile().mkdirs();
f.createNewFile();
}
FileOutputStream out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
Uri uri = Uri.fromFile(f);
return uri;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); }
return null;
}
private Handler mHandler = new Handler();
private Runnable mResetCache = new Runnable() {
@Override
public void run() {
tv_fen.setDrawingCacheEnabled(false);
tv_fen.setDrawingCacheEnabled(true);
}
};
}
代码直接复制粘贴去修改即可,需要注意的是LinearLayout的背景颜色要设置为白色,虽然默认就是白色,但那只是android的渲染,截图的话就变成透明黑了。