Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Wednesday, 27 September 2017

Fragment Visible or not

Hello guys,


public class HomeFragment extends Fragment
{
private boolean isVisible;

private boolean isStarted;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home, container, false);

    
    return view;
}


@Override
public void onStart() {
    super.onStart();
    isStarted = true;
    if (isVisible)
    {
        // Do something
    }
}

@Override
public void onStop() {
    super.onStop();
    isStarted = false;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    isVisible = isVisibleToUser;
    if (isVisible && isStarted)
    {
        // Do something
    }
}

}


Thank you

Tuesday, 26 September 2017

Refresh fragment with interface

Hello friends,



ActivityMain.java

public class HomeActivity extends Activity  {


public OnFragmentPassDataListeners getFragmentRefreshListener() {
    return fragmentRefreshListener;
}

public void setFragmentPassDataListener(OnFragmentPassDataListeners fragmentRefreshListener) {
    this.fragmentRefreshListener = fragmentRefreshListener;
}

private OnFragmentPassDataListeners fragmentRefreshListener;
private Button btnrefresh;


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

btnrefresh = (Button)findViewById(R.id.btn);
btnrefresh.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (getFragmentRefreshListener() != null) {
    getFragmentRefreshListener().onPassData("Hello Samset");
}
    }
});


}




FragmentHome.java


public class FragmentHome extends Fragment  {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
   View  view = inflater.inflate(R.layout.fragment_home, container, false);
    ((HomeActivity) getActivity()).setFragmentPassDataListener(new OnFragmentPassDataListeners() {

        @Override
        public void onPassData(String data) {
           Log.e("TAG"," Your massege"+data);
        }
    });
    initView(view);
    return view;
}





}



Thank you


Sunday, 23 July 2017

Firebase Authentication and Rules in android

Hello friends, in this  blog, we will see how we can make User Authentication and apply Rules in Android by using Firebase as our Application back end.

Integrating Firebase Auth

If you integrate firebase auth in your app so follow all instruction carefully. Fist you create a new Android Project.

 


Now you go to Tool menu Tool>Firebase and now you see right side open Firebase Assistense and now go to Authentication options and click "Email and password authentication".






Now you click Connect to firebase . When click Connect to Firebase then open browser if you not login, now login your account then click "Add firebase Authentication to your app". See your gradle and left side project structure  add json file and code is automatic integrated and create your project on firebase check your project https://firebase.google.com/



Now add some code in your app's

MainActivity.java


package com.samset.firebaseauthentication;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    private EditText etUserId, etPassword;
    private AppCompatButton btnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAuth = FirebaseAuth.getInstance();
        initView();


        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userId = etUserId.getText().toString();
                String password = etPassword.getText().toString();

                loginUser(userId, password);
            }
        });
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.e("TAG", "User:signed_in:" + user.getUid());

                    startActivity(new Intent(MainActivity.this, DataUploadActivity.class));

                } else {
                    // User is signed out
                    Log.e("TAG", "User:signed_out");
                }
            }
        };

    }

    private void loginUser(String user, String pass) {
        mAuth.signInWithEmailAndPassword(user, pass)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.e("TAG", "signInWithEmail:onComplete:" + task.isSuccessful());
                        if (!task.isSuccessful()) {

                            Toast.makeText(MainActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
                            Log.e("TAG", "signInWithEmail:failed", task.getException());
                        } else {
                            Log.e("TAG", "signInWithEmail:success");
                            Toast.makeText(MainActivity.this, "Successfully Login", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(MainActivity.this, DataUploadActivity.class));
                        }
                    }
                });
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    private void initView() {
        etPassword = (EditText) findViewById(R.id.et_password);
        etUserId = (EditText) findViewById(R.id.et_username);
        btnLogin = (AppCompatButton) findViewById(R.id.btnLogin);

    }
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="com.samset.firebaseauthentication.MainActivity">
    <TextView
        android:textColor="#000"
        android:text="Firebase Authentication"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="100dp"
        android:hint="User Id" />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:hint="Password" />

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:text="Login" />

</LinearLayout>

Go to firebase console and click left menu Authentication.........


Now see three tab go to SIGN IN METHOD

Now click Email and Passsword row and enable toggle see below screenshot
 

 Finally  go to USERS tab and add your user account like abc@gmailcom and password 123456. see below screenshot


Now you complete authentication process launch your app and test firebase auth.

 DataUploadActivity.java

 package com.samset.firebaseauthentication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.EditText;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.HashMap;
import java.util.Map;

public class DataUploadActivity extends AppCompatActivity {
    private DatabaseReference database;
    private FirebaseAuth mAuth;
    private EditText etUser, etcontact;
    private AppCompatButton btnRegi,btnLogout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_upload);
        mAuth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance().getReference("Testing");
        etcontact = (EditText) findViewById(R.id.et_contact);
        etUser = (EditText) findViewById(R.id.et_user);
        btnRegi = (AppCompatButton) findViewById(R.id.btnRegi);
        btnLogout = (AppCompatButton) findViewById(R.id.btnlogout);


        btnRegi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String,String> map=new HashMap<String, String>();
                map.put("test",etUser.getText().toString());
                database.child("User").setValue(map);

            }
        });

        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAuth.signOut();
                startActivity(new Intent(DataUploadActivity.this, MainActivity.class));
                finish();

            }
        });
    }
}

dataupload_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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.samset.firebaseauthentication.DataUploadActivity">
    <LinearLayout
        android:gravity="center"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="8dp">
        <EditText
            android:id="@+id/et_user"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:hint="Name" />

        <EditText
            android:id="@+id/et_contact"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="10dp"
            android:inputType="number"
            android:hint="Contact" />

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btnRegi"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="Send Data" />

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btnlogout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="Logout" />


    </LinearLayout>
</android.support.constraint.ConstraintLayout>








See firebase database if user login with auth



Thank you


Saturday, 1 July 2017

Why Nougat does not allow passing file:// with Intent

Hello friends


Android Nougat is almost be publicly released. And as an Android developer, we need to prepare ourself to adjust targetSdkVersion to the latest one, 24, to let everything works perfectly on the newest release of Android.


You may be curious why Android team decide to change this behavior. Actually there is a good reason behind.
If file path is sent to the target application (Camera app in this case), file will be fully accessed through the Camera app's process not the sender one.


But let's consider thoroughly, actually Camera is launched by our application to take a photo and save as a file on our app's behalf. So the access right to that file should be our app's not Camera's. Every operation did with the file should be done through our application not by Camera app itself.

And that's why file:// is now prohibited on targetSdkVersion 24 to force every developer to do this task in the proper way.


Solution 

So if file:// is not allowed anymore, which approach should we go for? 
The answer is we should send the URI through content:// scheme instead which is the URI scheme for Content Provider. In this case, we would like to share an access to a file through our app so FileProvider is needed to be implemented. Flow is now changed like below:







And now, with FileProvider, file operation would be done through our app process like it supposes to be !
It is quite easy to implement FileProvider on your application. 

First you need to add a FileProvider <provider> tag in AndroidManifest.xml under <application> tag like below:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="android.support.v4.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>
    </application>
</manifest>



And then create a provider_paths.xml file in xml folder under res folder. Folder may be needed to create if it doesn't exist.
The content of the file is shown below. It describes that we would like to share access to the External Storage at root folder (path=".") with the name external_files.


res/xml/provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>


Done! FileProvider is now declared and be ready to use.
The final step is to change the line of code below in MainActivity.java


Uri photoURI = Uri.fromFile(createImageFile());

to

Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
        BuildConfig.APPLICATION_ID + ".provider",
        createImageFile());



And .... done ! Your application should now work perfectly fine on any Android version including Android Nougat


If you not understand above process don't worry i describe with sample follow some easy steps....


MainActivity.java

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static android.R.attr.path;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private int REQUEST_CAMERA = 101;
    private int PIC_CROP = 102;
    private Uri photoURI = null;
    private String IMAGE_DIRECTORY_NAME = "sample";
    //String path;

   
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.iv);
        findViewById(R.id.btncamera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePicture();
            }
        });
    }

    private void takePicture() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                File photoFile = getOutputMediaFile();
                photoURI = FileProvider.getUriForFile(MainActivity.this, getString(R.string.file_provider_authority), photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_CAMERA);
            }
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            photoURI = getOutputMediaFileUri();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(intent, REQUEST_CAMERA);

        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == AppCompatActivity.RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageView.setImageURI(photoURI);
                 
                } else {
                    try {

                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 8;
                        final Bitmap bitmap = BitmapFactory.decodeFile(photoURI.getPath(), options);
                        //imageView.setImageBitmap(bitmap);
                       
                        // If you want croping use this
                       
performCrop(photoURI);
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                }
            } else if (requestCode == PIC_CROP) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Uri selectedImageUri = data.getData();
                    imageView.setImageURI(selectedImageUri);
                    Log.e("TAG", " onResult after crop pixel " + selectedImageUri);

                } else {
                    Uri selectedImageUri = data.getData();


                    if (selectedImageUri != null) {
                        imageView.setImageURI(selectedImageUri);

                    } else {

                        Bitmap selectedBitmap = (Bitmap) data.getExtras().get("data");
                        imageView.setImageBitmap(selectedBitmap);
                    }
                }

            }
        }
    }

    private void performCrop(Uri selectedImageUri) {
        try {
            Log.e("TAG", " get data crop " + selectedImageUri);
            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            // indicate image type and Uri
           
cropIntent.setDataAndType(selectedImageUri, "image/*");
            // set crop properties
           
cropIntent.putExtra("crop", "true");
            // indicate aspect of desired crop
           
cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            // indicate output X and Y
           
cropIntent.putExtra("outputX", 128);
            cropIntent.putExtra("outputY", 128);
            // retrieve data on return
           
cropIntent.putExtra("return-data", true);
            // start the activity - we handle returning in onActivityResult
           
if (getPackageManager() != null) {
                startActivityForResult(cropIntent, PIC_CROP);
            }

        } catch (Exception anfe) {
            anfe.printStackTrace();
            String errorMessage = "Whoops - your device doesn't support the crop action!";
            Log.e("TAG", " Croping error " + errorMessage);

        }
    }

    /**
     * Creating file uri to store image/video
     */
   
public Uri getOutputMediaFileUri() {
        return Uri.fromFile(getOutputMediaFile());
    }

    /*
     * returning image / video
     */
   
private File getOutputMediaFile() {

        // External sdcard location
       
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
       
if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "+ IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
       
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");

        return mediaFile;
    }
}


AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo.camerademos"
>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="@string/file_provider_authority"
            android:exported="false"
            android:grantUriPermissions="true"
>
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_provider_path"
/>
        </provider>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Thank you

FullSourceCode DownloadNougatCamera



Sample






Sunday, 30 April 2017

Set random color background in android

Hello friends,



activity_main.xml



<?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"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">


    <FrameLayout
        android:id="@+id/flayout"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_alignParentBottom="true">

     
    </FrameLayout>

</RelativeLayout>


set random color


ActivityMain.java



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

FrameLayout flayout=(FrameLayout)findViewById(R.id.flayout);


 int randomAndroidColor = color[new Random().nextInt(color.length)];

 GradientDrawable bgShape = (GradientDrawable) holder.llCircle.getBackground();

Random random = new Random();

flayout.setColor(Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256)));

if you want use own color list then enable below line

flayout.setColor(randomAndroidColor);




}



FloatingActionMenu in android

Hello guys,
 Today we are learn about how to create FloatingActionMenu in android.


ActivityMain.java

package com.samset.floatingactionmenu;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

    private FloatingActionButton fabmain, fabdelete, fabsettings, fabfavorite;
    private LinearLayout fabLayoutFavorite, fabLayoutSettings, fabLayoutDelete;
    private View fabBGLayout;
    boolean isFABOpen = false;

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


        fabLayoutDelete = (LinearLayout) findViewById(R.id.fabLayoutLike);
        fabLayoutSettings = (LinearLayout) findViewById(R.id.fabLayoutSettings);
        fabLayoutFavorite = (LinearLayout) findViewById(R.id.fabLayoutdelete);
        fabmain = (FloatingActionButton) findViewById(R.id.fab);
        fabdelete = (FloatingActionButton) findViewById(R.id.fabDelete);
        fabsettings = (FloatingActionButton) findViewById(R.id.fabSettings);
        fabfavorite = (FloatingActionButton) findViewById(R.id.fabLike);
        fabBGLayout = findViewById(R.id.fabBGLayout);

        fabmain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isFABOpen) {
                    showMenu();
                } else {
                    closeMenu();
                }
            }
        });

        fabBGLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeMenu();
            }
        });
    }

    private void showMenu() {
        isFABOpen = true;
        fabLayoutFavorite.setVisibility(View.VISIBLE);
        fabLayoutSettings.setVisibility(View.VISIBLE);
        fabLayoutDelete.setVisibility(View.VISIBLE);
        fabBGLayout.setVisibility(View.VISIBLE);

        fabmain.animate().rotationBy(45);
        fabLayoutFavorite.animate().translationY(-getResources().getDimension(R.dimen.margin_55));
        fabLayoutSettings.animate().translationY(-getResources().getDimension(R.dimen.margin_100));
        fabLayoutDelete.animate().translationY(-getResources().getDimension(R.dimen.margin_145));
    }

    private void closeMenu() {
        isFABOpen = false;
        fabBGLayout.setVisibility(View.GONE);
        fabmain.animate().rotationBy(-45);
        fabLayoutFavorite.animate().translationY(0);
        fabLayoutSettings.animate().translationY(0);
        fabLayoutDelete.animate().translationY(0).setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                if (!isFABOpen) {
                    fabLayoutFavorite.setVisibility(View.GONE);
                    fabLayoutSettings.setVisibility(View.GONE);
                    fabLayoutDelete.setVisibility(View.GONE);
                }

            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
    }

    @Override
    public void onBackPressed() {
        if (isFABOpen) {
            closeMenu();
        } else {
            super.onBackPressed();
        }
    }
}

activity_main.xml

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.samset.floatingactionmenu.MainActivity"
    tools:ignore="VectorDrawableCompat">

    <View
        android:id="@+id/fabBGLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/viewBackground"
        android:visibility="gone" />


    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true">

        <LinearLayout
            android:id="@+id/fabLayoutdelete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_marginBottom="@dimen/margin_25"
            android:layout_marginRight="@dimen/margin_25"
            android:clipToPadding="false"
            android:gravity="center_vertical"
            android:padding="@dimen/standard_12"
            android:visibility="gone">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fabDelete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                app:fabSize="mini"
                app:srcCompat="@drawable/ic_delete" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/fabLayoutSettings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_marginBottom="@dimen/margin_25"
            android:layout_marginRight="@dimen/margin_25"
            android:clipToPadding="false"
            android:gravity="center_vertical"
            android:padding="@dimen/standard_12"
            android:visibility="gone">

            <TextView
                android:textColor="#FFF"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Settings" />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fabSettings"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                app:fabSize="mini"
                app:srcCompat="@drawable/ic_settings" />
        </LinearLayout>


        <LinearLayout
            android:id="@+id/fabLayoutLike"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_marginBottom="@dimen/margin_25"
            android:layout_marginRight="@dimen/margin_25"
            android:clipToPadding="false"
            android:gravity="center_vertical"
            android:padding="@dimen/standard_12"
            android:visibility="gone">
            <TextView
                android:textColor="#FFF"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Like" />
            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fabLike"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:tint="@android:color/white"
                app:fabSize="mini"
                app:srcCompat="@drawable/ic_favorite" />
        </LinearLayout>


        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_marginBottom="@dimen/fab_margin"
            android:layout_marginRight="@dimen/fab_margin"
            android:clipToPadding="false"
            android:gravity="center_vertical"
            android:padding="@dimen/standard_12">


            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom|end"
                android:gravity="center_vertical"
                app:fabSize="normal"
                app:srcCompat="@drawable/ic_add" />
        </LinearLayout>
    </FrameLayout>
</RelativeLayout>


color.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="viewBackground">#CC000000</color>


</resources>

dimens.xml


<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
   
<dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>


    <dimen name="_50sdp">55dp</dimen>
    <dimen name="standard_12">12dp</dimen>
    <dimen name="margin_25">25dp</dimen>
    <dimen name="margin_55">55dp</dimen>
    <dimen name="margin_100">100dp</dimen>
    <dimen name="margin_145">145dp</dimen>
    <dimen name="fab_margin">16dp</dimen>

</resources>

Live Sample    





Thank you
 See FullSorceCode download hereFloatingActionMenu-master



Monday, 6 March 2017

Android app shortcut

Hello friends,

There comes  new features and Android Nougat 7.1 is no different. One of these new features is App Shortcuts. App Shortcuts allow the user to access primary actions in your app straight from the launcher, taking the user deep into your application, by long pressing on your app icon.
Main point of shortcut use..


  1. App Shortcuts are great for exposing actions of your app and bring back users into your flow
  2. They can be static or dynamic
  3. Static are set in stone once you define them (you can only update them with an app redeploy)
  4. Dynamic can be changed on the fly
  5. You can create a back stack of activities once you open one through a shortcut
  6. Shortcuts can be reordered, but only in their respective type and static shortcuts will come always at the bottom as they're added first (there's no rank property to be defined on them)
  7. The labels of the shortcuts are CharSequence so you can manipulate them through spans.
Android app shortcut basically two type-

1. Static shortcut
2. Dynamic shortcut

How to add static shortcut: 

First you create a new project or existing project go to android manifest.xml and add below line


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="samset.appshortcut">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <meta-data
                android:name="android.app.shortcuts"
                android:resource="@xml/shortcut" />
        </activity>
     
    </application>

</manifest>

Now you create in a xml folder in res folder and create file shortcut.

shortcut.xml

<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
    <shortcut
        android:enabled="true"
        android:icon="@drawable/ic_stars"
        android:shortcutDisabledMessage="@string/disabled_message"
        android:shortcutId="id_static"
        android:shortcutLongLabel="@string/static_label"
        android:shortcutShortLabel="@string/launcher_label">
        <!-- You see here i define two intent i think you confuse why i use two intent so i confirm first intent use when your app launch and you press back then you come on MainActivity-->
        <intent
            android:action="android.intent.action.Main"
            android:targetClass="samset.appshortcut.MainActivity"
            android:targetPackage="samset.appshortcut" />
        <!-- Second intent use when you long press and open shortcut then you redirect your target actvity(StaticActivity)-->
        <intent
            android:action="android.intent.action.VIEW"
            android:targetClass="samset.appshortcut.StaticShortcutActivity"
            android:targetPackage="samset.appshortcut" />
    </shortcut>

    <shortcut
        android:enabled="true"
        android:icon="@drawable/ic_settings"
        android:shortcutDisabledMessage="@string/disabled_message"
        android:shortcutId="id_setting"
        android:shortcutLongLabel="@string/setting_label"
        android:shortcutShortLabel="@string/launcher_label_settings">
        <intent
            android:action="android.intent.action.Main"
            android:targetClass="samset.appshortcut.MainActivity"
            android:targetPackage="samset.appshortcut" />
       <intent
            android:action="android.intent.action.VIEW"
            android:targetClass="samset.appshortcut.StaticShortcutActivity"
            android:targetPackage="samset.appshortcut" />
    </shortcut>
</shortcuts>

  • enabled: as the name states, whether the shortcut is enabled or not. If you decide to disable your static shortcut you could either set this to false, or simply remove it from the <shortcuts> set
  • icon: the icon shown on the left hand side of the shortcut. In my case, I created a simple Vector Drawable from within Android Studio and assigned it as an icon
  • shortcutDisabledMessage: when you disable your shortcut, it will disappear from the ones that the user can reveal by long pressing your application icon, but one can pin a shortcut to the launcher (by long pressing and dragging it on the desired launcher page), so when disabled the pinned shortcut will appear greyed out and upon tapping it a Toast with this message will appear
  • shortcutLongLabel: longer text of the shortcut shown when the launcher has enough space
  • shortcutShortLabel: a concise description of the shortcut. The field is mandatory. Most probably this will be the one which will appear on your launcher
  • intent: here you define your intent (or more intents) that your shortcut will open upon being tapped


How to add dynamic shortcut: 

MainActivity.java

package samset.appshortcut;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
    private ShortcutManager shortcutManager;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        shortcutManager = getSystemService(ShortcutManager.class);
        if (Build.VERSION.SDK_INT >= 25) {
            createShorcut();
        }
    }


    @TargetApi(25)
    private void createShorcut() {

        ShortcutInfo webshart = new ShortcutInfo.Builder(this, "shortcutweb")
                .setShortLabel("web")
                .setLongLabel("Website")
                .setIcon(Icon.createWithResource(this, R.drawable.ic_touch_app))
                .setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://samsetdev.blogspot.in/")))
                .setRank(0)
                .build();

        ShortcutInfo dynamicShortcut = new ShortcutInfo.Builder(this, "dynamicshortcut")
                .setShortLabel("Dynamic")
                .setLongLabel("Dynamic Activity")
                .setIcon(Icon.createWithResource(this, R.drawable.ic_touch_app))
                .setIntents(new Intent[]{new Intent(Intent.ACTION_MAIN, Uri.EMPTY, this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK),
                        new Intent(DynamicActivity.ACTION)
                })
                .setRank(1)
                .build();

        shortcutManager.setDynamicShortcuts(Arrays.asList(webshart, dynamicShortcut));
    }

    @TargetApi(25)
    private void removeShorcuts() {
        ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
        shortcutManager.disableShortcuts(Arrays.asList("shortcut1"));
        shortcutManager.removeAllDynamicShortcuts();
    }
}


add some line of code in manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="samset.appshortcut">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <meta-data
                android:name="android.app.shortcuts"
                android:resource="@xml/shortcut" />
        </activity>
        <activity
            android:name=".StaticShortcutActivity"
            android:label="@string/static_label" />

        <activity
            android:name=".DynamicActivity"
            android:label="@string/dynamic_label">
            <intent-filter>
                <action android:name="samset.appshortcut.DYNAMIC_SHORTCUT" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 


Thank you
FullSourcecode