用于打开共享意图的代码
String xtype = "image/*";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType(xtype);
Uri uri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", new File(tmpImageUri.getPath()));
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share via"));
它显示了这样的共享意图对话框
但是现在我想要这样
是否可以自定义“共享意图”对话框?
答案 0 :(得分:3)
是的,可以创建自定义共享对话框。您只需要获取IntentActivity
列表并根据需要自定义即可。对于Sample,您可以执行以下操作。
第1步:准备意图
String urlToShare = "https://play.google.com/store/apps/details?id=com.yourapp.packagename";
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_SUBJECT, "If any extra"); // NB: has no effect!
intent.putExtra(Intent.EXTRA_TEXT, "Let me recommend you this application \n\n" + urlToShare);
第2步:获取活动列表并在ListAdapter中进行设置。
final List<ResolveInfo> activities = getPackageManager().queryIntentActivities(intent, 0);
List<DialogItem> appNames = new ArrayList<DialogItem>();
for (ResolveInfo info : activities) {
appNames.add(new DialogItem(info.loadLabel(getPackageManager()).toString(),
info.loadIcon(getPackageManager())));
}
final List<DialogItem> newItem = appNames;
ListAdapter adapter = new ArrayAdapter<DialogItem>(activity,
android.R.layout.select_dialog_item, android.R.id.text1, newItem) {
public View getView(int position, View convertView, ViewGroup parent) {
//Use super class to create the View
View v = super.getView(position, convertView, parent);
TextView tv = v.findViewById(android.R.id.text1);
tv.setText(newItem.get(position).app);
tv.setTextSize(15.0f);
//Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(newItem.get(position).icon, null, null, null);
//Add margin between image and text (support various screen densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
tv.setCompoundDrawablePadding(dp5);
return v;
}
};
注意:-请确保DialogItem
是您的模型类,并且必须在应用中创建。
public class DialogItem {
public String app = "";
public Drawable icon;
public DialogItem(String name, Drawable drawable) {
app = name;
icon = drawable;
}
}
第3步:在您的AlertDialog中设置该适配器
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Custom Sharing Dialog");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
ResolveInfo info = activities.get(item);
if (info.activityInfo.packageName.equals("com.facebook.katana")) {
Toast.makeText(activity, "Facebook Selected ", Toast.LENGTH_LONG).show();
} else {
// start the selected activity
Log.i(TAG, "Hi..hello. Intent is selected");
intent.setPackage(info.activityInfo.packageName);
startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
输出:-
使用AlertDialog的自定义可共享对话框,但是您可以根据需要通过使用自定义布局并创建Dialog类来进行所有设置(UI,选择,主题等)