Как активировать кнопку "Поделиться" в приложении для Android?
я хочу добавить кнопку "Поделиться" в свое приложение для Android.
Вот так
Я добавил кнопку "Поделиться", но кнопка не активна. Я нажимаю, но ничего не происходит.
Мой код в MainActivity.java:
private ShareActionProvider mShareActionProvider;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.share_menu, menu);
getMenuInflater().inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.share_menu);
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share_menu).getActionProvider();
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return true;
}
{
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Text");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(sharingIntent, "Share using"));
}
Я хочу поделиться текстом на моей первой вкладке (first_tab.xml) или второй вкладке (second_tab.xml).
Код на вкладке (xml) (при необходимости):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background_color"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity$DummySectionFragment" >
<TextView
android:id="@+id/section_label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/text"
android:textColor="@color/text_color" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:src="@drawable/sprite" />
Переведено автоматически
Ответ 1
Добавьте Button
и по щелчку Button
добавьте этот код:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
Полезные ссылки:
Ответ 2
Создайте кнопку с идентификатором "Поделиться" и добавьте следующий фрагмент кода.
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Your body here";
String shareSub = "Your subject here";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using"));
}
});
Приведенный выше фрагмент кода откроет окно выбора общего доступа при нажатии кнопки "Поделиться".
Однако обратите внимание...Фрагмент кода общего доступа может выдавать не очень хорошие результаты при использовании эмулятора. Для получения реальных результатов запустите фрагмент кода на устройстве Android, чтобы получить реальные результаты.
Ответ 3
в kotlin :
val sharingIntent = Intent(android.content.Intent.ACTION_SEND)
sharingIntent.type = "text/plain"
val shareBody = "Application Link : https://play.google.com/store/apps/details?id=${App.context.getPackageName()}"
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "App link")
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody)
startActivity(Intent.createChooser(sharingIntent, "Share App Link Via :"))
Ответ 4
Поделитесь любым файлом, как показано ниже (Kotlin) :
сначала создайте папку с именем xml
в res
папке и создайте новый файл ресурсов XML с именем provider_paths.xml
и поместите в него приведенный ниже код :
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
name="files"
path="."/>
<external-path
name="external_files"
path="."/>
</paths>
теперь перейдите в manifests
папку и откройте AndroidManifest.xml
, а затем поместите приведенный ниже код внутрь <application>
тега :
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>
теперь вы помещаете приведенный ниже код в setOnLongClickListener
:
share_btn.setOnClickListener {
try {
val file = File("pathOfFile")
if(file.exists()) {
val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
val intent = Intent(Intent.ACTION_SEND)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setType("*/*")
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent)
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
toast("Error")
}
}