Pages

Thursday, March 22, 2018

How To Open Social Media with floating button

How to Open Social Media with FloatingActionButton

# Build.gradle

We need support design dependencies. In build.gradle (module:app) section add dependencies.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:design:26.+'
}

# In activity_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
   xmlns:app="http://schemas.android.com/apk/res-auto" 
   xmlns:tools="http://schemas.android.com/tools"   
   android:layout_width="match_parent" 
   android:layout_height="match_parent"
    tools:context="com.spidytechnology.floatingactionbutton.MainActivity">

    <android.support.design.widget.FloatingActionButton   
     android:id="@+id/fab"    
    android:layout_width="wrap_content"   
     android:layout_height="wrap_content" 
       android:layout_alignParentBottom="true"    
    android:layout_alignParentRight="true"     
   android:layout_marginBottom="40dp"  
      android:layout_marginLeft="11dp"  
      android:layout_marginRight="11dp"  
      app:srcCompat="@drawable/ic_social_media"        />

</RelativeLayout>

# MainActivity

package com.spidytechnology.floatingactionbutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View view) {
        //Add Action when floatingActionButton Clicked
        Intent facebookIntent = getOpenFacebookIntent(MainActivity.this);
        startActivity(facebookIntent);
    }

    private Intent getOpenFacebookIntent(MainActivity context) {

        try {
            context.getPackageManager()
                    .getPackageInfo("example.com.mkc_11", 0); 
    return new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://www.facebook.com/sidsam.shivashailendra")); 
  } catch (Exception e) {
            return new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://www.facebook.com/sidsam.shivashailendra"));     }
                   }
      });
            }     }