- Adding a Share Action to Android Application
- Android Example: How to Add Easy Share Action in Android ActionBar and Button
- Реализация простого обмена данными. Кнопка “поделиться” в android приложении
- [wpanchor >
- Обновление макета меню в android приложении
- [wpanchor >
- Установка интента для обмена данными между android приложениями
- Share Button in Android App
- Complete Code to Create Share Button in Android App
- Adding Share Button – Android Studio
- Adding Share Button – Android Studio
- #Step 02 setOnClickListener method – Adding Share Button – Android Studio
Adding a Share Action to Android Application
In this tutorial, you will learn to implement an effective and user friendly share action to android app. You can add android share action anywhere in your app. Here I have added share action in actionbar/toolbar and on button’s click event. If user clicks the share button from actionbar/toolbar, many options will be available there to share like email, gmail, facebook, twitter and so on. If you want to add subtitle to your app toolbar/appbar follow Setting Android ActionBar Subtitle and Color tutorial and if you want to make custom material design appbar follow Android Material Design ActionBar/App Bar tutorial.
Here we will share/send message to friends via our android application with message title, description. For subject you need to use EXTRA_SUBJECT and EXTRA_TEXT for text message.
Related:
Sending Email from Android Application
How to Add Spinner (Dropdown List) to Android ActionBar/Toolbar
Implementing SearchView in Android ActionBar
Android Example: How to Add Easy Share Action in Android ActionBar and Button
Create a new android project called android easy share action. Open your app main XML layout file and add a button or textview with onClick attribute. I have added a TextView with onClick attribute. Following is the complete content of XML layout file.
res/layout/activity_main.xml
To add share action in android appbar/toolbar you need to create a XML file in res/menu directory and add an items with attributes like android:id, android:actionProviderClass, android:icon, android:title, app:showAsAction. Action_menu.xml file will look like below.
res/menu/action_menu.xml
Now open your java activity file and add override onCreateOptionsMenu and onOptionsItemSelected methods to implement share action to android actionbar. In onOptionsItemSelected method you need to add some code to open share option and share something to the friends. If you want to share something when user click the button you need to add little bit code in android button onClick like the below. Following is the complete code of java activity file.
That’s all. Run your Adding a Share Action to Android Application and click on the share icon from action bar or click the share button. There, you will see many option to share, choose one of them and then share to your friends.
Реализация простого обмена данными. Кнопка “поделиться” в android приложении
Реализация эффективного и удобного действия “поделиться” в ActionBar стала еще проще с введением ActionProvider в Android 4.0 (API Уровень 14). ActionProvider , сразу после присоединения к пункту меню в панели действий, обрабатывает как внешний вид, так и поведение этого элемента. В случае ShareActionProvider , вы предоставляете интент “обмена” и он сделает все остальное.
Примечание: ShareActionProvider доступен начиная с Уровня API 14 и выше.
Рисунок 1. ShareActionProvider в приложении Галерея.
[wpanchor >
Обновление макета меню в android приложении
Чтобы начать работу с ShareActionProviders , определите android:actionProviderClass атрибут для соответствующего в вашем ресурс меню файле:
Это делегирует ответственность за внешний вид элемента и функции в ShareActionProvider . Однако, вам нужно будет сообщить провайдеру, чем вы хотели бы поделиться.
[wpanchor >
Установка интента для обмена данными между android приложениями
Чтобы ShareActionProvider функционировал, необходимо предоставить интент для обмена. Этот интент должен быть таким же, как описано в уроке Отправка простых данных в другие приложения , с действием ACTION_SEND и дополнительными данными установленных с помощью EXTRA_TEXT и EXTRA_STREAM . Чтобы назначить интент обмена, сначала найдите соответствующий MenuItem в своем ресурсе меню в вашем Activity или Fragment . Далее, вызовите MenuItem.getActionProvider() для получения экземпляра ShareActionProvider . Используйте setShareIntent() для обновления интента обмена, связанного с этим элементом действия. Вот пример:
private ShareActionProvider mShareActionProvider; . @Override public boolean onCreateOptionsMenu(Menu menu) < // Inflate menu resource file. getMenuInflater().inflate(R.menu.share_menu, menu); // Locate MenuItem with ShareActionProvider MenuItem item = menu.findItem(R.id.menu_item_share); // Fetch and store ShareActionProvider mShareActionProvider = (ShareActionProvider) item.getActionProvider(); // Return true to display menu return true; >// Call to update the share intent private void setShareIntent(Intent shareIntent) < if (mShareActionProvider != null) < mShareActionProvider.setShareIntent(shareIntent); >>
Вам необходимо установить интент обмена только один раз, во время создания вашего меню, или же вы можете установить его, а затем обновлять его по мере изменений пользовательского интерфейса. Например, при просмотре фотографий в полноэкранном режиме в приложении Галерея, интент обмена изменяется, когда вы переключаетесь между фотографиями.
Если не указано иное, этот контент распространяется под лицензией Creative Commons Attribution 2.5. Для получения дополнительной информации и ограничений, см. Лицензия контента.
Share Button in Android App
This tutorial explains step by step for how to add a Share Button/ Action in Android Application via Android Studio. Share button will help share our app content.
Please follow the steps below in order to add Share Button/ Action in Android Application:
1.Go to Android studio. Remove “hello world” text and add a Button.
2.Click on the button icon and drag it to the center of the screen.
3.Click on the text tab. Change “Button” to “Share it”.
4.Go to MainActivity.java. Inside the OnClickListener, add an intent to force the application.
5.Change shareBody into shareSub.
6.Go to the live device for the explanation. You can see the button.
7.On pressing the button, you will see a pop-up screen.
8.Copy the screen to the clipboard.
9.Now click on messages.
10. Add recipients and share your subject and description.
Complete Code to Create Share Button in Android App
app > res > layout > activity_main.xml
app > java > com.stechies.shareData.MainActivity > MainActivity.java
package com.stechies.shareData; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity < Button bt; @Override protected void onCreate(Bundle SavedInstanceState) < super.onCreate(SavedInstanceState); setContentView(R.layout.activity_main); bt = (Button) findViewById(R.Id.button); bt.setOnClickListner(new View.OnClickListner () < @Override protected void onClick(View v)< Intent myIntent = new Intent(Intent.ACTION_SEND); myIntent.setType("text/plain"); String body = "Your body here"; String sub = "Your Subject"; myIntent.putExtra(Intent.EXTRA_SUBJECT,sub); myIntent.putExtra(Intent.EXTRA_TEXT,body); startActivity(Intent.createChooser(myIntent, "Share Using")) >>); > >
- What is Android?
- Android ScrollView
- Android Training Tutorials for Beginners
- Downloading and Install Java JDK
- Android Activity Lifecycle Diagram
- Android Fragment Example
- Android Activity Lifecycle Diagram
- Android Intent Service Example
- Android Explicit And Implicit Intent
- Android UI Design
- Android Drag and Drop ListView Example
- Android Studio Facebook Integration
- Android Wifi Example
- Publish Android App
- Android Alert Dialog Example
- Android DatePicker Dialog Example
- Android Animation Fade In & Out Example
- Android App Share Button
Adding Share Button – Android Studio
Hello Android Lovers, In this “Adding Share Button – Android Studio” article, I am going to discuss how to add a share button. So lets start “Adding share button – Android Studio” article in Android Tutorails.
If you are a newbie to Android. Follow and refer articles.
Adding Share Button – Android Studio
First of all, we need to create a button in the layout file. So here is the code for that.
After you creating the layout file, then go the Java file.
In your Java file, first add properties.
private Button btnShare; public static String PACKAGE_NAME;
We need the package name to implement the share option.
Then define in the onCreate() method.
btnShare= findViewById(R.id.btnShare); PACKAGE_NAME = getApplicationContext().getPackageName();
We are going to develop share option when the button click. So we have to implement the setOnClickListener method.
#Step 02 setOnClickListener method – Adding Share Button – Android Studio
First of all, I am going to create another method to implement share option. I am calling that as ShareMe(). Here is the ShareMe() Code.
private void ShareMe(String url) < Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); String value = url + PACKAGE_NAME; intent.putExtra(Intent.EXTRA_TEXT, value); startActivity(Intent.createChooser(intent,"Share Via")); >
In here I am creating a Intent and pass the ACTION_SEND. Then create a variable to set the URL and the package name.
When you assign this ShareMe() method, you have to pass the URL that you are going to share. In here I am going to share my Plays tore app.
After that we are going to implement the setOnClickListener() method. Here is the code for that.
Other articles from different categories.
- Android Studio Articles – https://builditmasters.com/category/android-studio/
- Android Studio Firebase Tutorial – https://builditmasters.com/category/android-studio-firebase-tutorial/
- C Programming – https://builditmasters.com/category/programming/
- Flutter – https://builditmasters.com/category/flutter/
- GitHub Tutorials – https://builditmasters.com/category/github/
- Java Programming – https://builditmasters.com/category/java-programming/
- MERN / MEVN Stacks – https://builditmasters.com/category/mern_mevn_stacks/
- Tech News – https://builditmasters.com/category/tech-news/
- Theory Lessons – https://builditmasters.com/category/theory-lessons/
- Adobe Tutorials – https://builditmasters.com/category/adobe-tutorials/
- Best Website for Programming – https://builditmasters.com/category/best-website-for-programming/
- Different Programming Styles – https://builditmasters.com/category/different-programming-styles/
- Earn Money – https://builditmasters.com/category/earn-money/
- Social Word – https://builditmasters.com/category/social-world/