Android

Android Local Broadcast Receiver

Simple Local broadcast receiver example

MainActivity

package com.example.eg.localbroadcastreciver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        // adding click event for the button
        findViewById(R.id.send_broadcast).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //the following code will be inside your service
                //creating intent MyTaskStatus
                Intent myIntent = new Intent("MyTaskStatus");
                myIntent.putExtra("MyMessage", "Hi");

                // Send broadcast
                LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(myIntent);

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();

        //register broadcast receiver for the intent MyTaskStatus
        LocalBroadcastManager.getInstance(this).registerReceiver(MyReceiver, new IntentFilter("MyTaskStatus"));

    }

    //Defining broadcast receiver
    private BroadcastReceiver MyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String message = intent.getStringExtra("MyMessage");

            Toast.makeText(MainActivity.this, "Received : "+message, Toast.LENGTH_SHORT).show();
        }
    };



    @Override
    protected void onStop() {
        super.onStop();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(MyReceiver);
    }

}

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: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="com.example.eg.localbroadcastreciver.MainActivity"
    android:orientation="vertical">


    <Button
        android:id="@+id/send_broadcast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Broadcast"/>


</LinearLayout>

 

————————————————————————————————————————————————————–

Another exaple

Here registering the broadcast receiver with the action

package com.example.eg.localbroadcastreciver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

public class Main2Activity extends AppCompatActivity {

    public static final String ACTION_DONE = "MyTaskService#ACTION_DONE";

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

        // adding click event for the button
        findViewById(R.id.send_broadcast).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //the following code will be inside your service
                // Create Intent to broadcast the task information.
                Intent intent = new Intent();
                intent.setAction(ACTION_DONE);
                intent.putExtra("msg", "Hi");

                // Send local broadcast, running Activities will be notified about the task.
                LocalBroadcastManager manager = LocalBroadcastManager.getInstance(Main2Activity.this);
                manager.sendBroadcast(intent);

            }
        });

    }

    // BroadcastReceiver to get information from MyTaskService about task completion.
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //no need to check action again
            //if (intent.getAction().equals(ACTION_DONE)) {

            String msg = intent.getStringExtra("msg");

            Toast.makeText(context,"Broadcast received message : "+ msg, Toast.LENGTH_SHORT).show();
            //}
        }
    };

    @Override
    public void onStart() {
        super.onStart();

        //registering intent filter based on action
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_DONE);

        LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);
        manager.registerReceiver(mReceiver, filter);
    }



    @Override
    protected void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    }

}

activity_main2.xml

<?xml version="1.0" encoding="utf-8"?>
<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: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="com.example.eg.localbroadcastreciver.Main2Activity">

    <Button
        android:id="@+id/send_broadcast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Broadcast"/>

</RelativeLayout>

 

 

ref: https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html

By bm on July 13, 2016 | Android | A comment?

Android AsyncTask

“AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.” – developer.android

Async task class definition

class AsyncTaskClassName extends AsyncTask<argumentType, progrssValueType, taskResultType> {

     //inputarg can contain array of values
     protected taskResultType doInBackground(argumentType... inputarg) {

         //-------
         //-- Your Long running task here ----

         int count = inputarg.length;

         for (int i = 0; i < count; i++) {
             Log.i("from Async task", inputarg[i] );
         }

         //-------

         publishProgress(progrssValue));


         return taskresult;
     }

     protected void onProgressUpdate(progrssValueType... progress) {

         //update the progress
         setProgressPercent(progress[0]);

     }
     
     //this will call after finishing the doInBackground function
     protected void onPostExecute(taskResultType result) {

         // Update the ui elements 
         //show some notification
         showDialog("Task done "+ result);

     }
 }

starting task

new AsyncTaskClassName().execute(arg1, arg2, etc );

 

Or we can execute directly

new AsyncTask<Void, Void, Void>() {

    @Override
    protected Void doInBackground(Void... params) {
        //long running task
        return null ;
    }


    @Override
    protected void onPostExecute(Void x) {
        //update the ui elemets
    }
}.execute();

 

 

ref : https://developer.android.com/reference/android/os/AsyncTask.html

By bm on | Android | 3 comments

Pinch gesture in Recycler View grid layout

Goal: Change grid layout on pinch gesture in recycler view

In this tutorial we will fetch images from gallery and show them in a grid layout in recycler view. You will be able to change layout on pinch gesture. Following are the screen shots of different layouts.

Screenshot_2016-06-29-15-39-23      Screenshot_2016-06-29-15-40-52    Screenshot_2016-06-29-15-39-01

 

Step 1:

Create a new project in android studio and add read external storage permission in AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Step 2:

add recycler view in layout file for the activity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:padding="5dp"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    tools:context=".PhotosActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_photos"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:scrollbars="vertical" />

</RelativeLayout>

Step 3:

Add code in activity. Here we are not checking if external storage permission is given or not for Android M and above. (You can add that in the code).

  1. Create three instances of GridLayoutManagers (first with 1 column,  2nd with 2 columns and 3rd with 3 columns).
  2. Get the instance of RecyclerView in activity’s onCreate()
  3. Add GridLayoutManager with 2 columns to it (by default we are keeping two columns)
  4. Create an adapter and add it to recycler view
  5. fetch photos from gallery and add to adapter and call notifyDatasetChanged() for the adapter.

Here is the activity code:

import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class PhotosActivity extends AppCompatActivity {

    private RecyclerView mRvPhotos;
    private ProgressDialog mProgressDialog;

    private List<String> mPhotoUris;
    private PhotosAdapter mPhotosAdapter;

    private GridLayoutManager mGridLayoutManager1, mGridLayoutManager2, mGridLayoutManager3;
    private RecyclerView.LayoutManager mCurrentLayoutManager;

    private ScaleGestureDetector mScaleGestureDetector;

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

        //setup progress dialog
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Fetching Photos...");
        mProgressDialog.setCancelable(false);

        //setup recycler view
        mRvPhotos = (RecyclerView) findViewById(R.id.rv_photos);

        if (mRvPhotos != null) {

            //initialize layout managers
            mGridLayoutManager1 = new GridLayoutManager(this, 1);
            mGridLayoutManager2 = new GridLayoutManager(this, 2);
            mGridLayoutManager3 = new GridLayoutManager(this, 3);

            //initialize photo uris list
            mPhotoUris = new ArrayList<>();

            //initialize adapter
            mPhotosAdapter = new PhotosAdapter(mPhotoUris);

            //set layout manager
            mCurrentLayoutManager = mGridLayoutManager2;
            mRvPhotos.setLayoutManager(mGridLayoutManager2);

            //set adapter
            mRvPhotos.setAdapter(mPhotosAdapter);

            //set scale gesture detector
            mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
                @Override
                public boolean onScale(ScaleGestureDetector detector) {
                    if (detector.getCurrentSpan() > 200 && detector.getTimeDelta() > 200) {
                        if (detector.getCurrentSpan() - detector.getPreviousSpan() < -1) {
                            if (mCurrentLayoutManager == mGridLayoutManager1) {
                                mCurrentLayoutManager = mGridLayoutManager2;
                                mRvPhotos.setLayoutManager(mGridLayoutManager2);
                                return true;
                            } else if (mCurrentLayoutManager == mGridLayoutManager2) {
                                mCurrentLayoutManager = mGridLayoutManager3;
                                mRvPhotos.setLayoutManager(mGridLayoutManager3);
                                return true;
                            }
                        } else if(detector.getCurrentSpan() - detector.getPreviousSpan() > 1) {
                            if (mCurrentLayoutManager == mGridLayoutManager3) {
                                mCurrentLayoutManager = mGridLayoutManager2;
                                mRvPhotos.setLayoutManager(mGridLayoutManager2);
                                return true;
                            } else if (mCurrentLayoutManager == mGridLayoutManager2) {
                                mCurrentLayoutManager = mGridLayoutManager1;
                                mRvPhotos.setLayoutManager(mGridLayoutManager1);
                                return true;
                            }
                        }
                    }
                    return false;
                }
            });

            //set touch listener on recycler view
            mRvPhotos.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    mScaleGestureDetector.onTouchEvent(event);
                    return false;
                }
            });

            //fetch photos from gallery
            new FetchPhotosTask(this).execute();
        }
    }

    public static class FetchPhotosTask extends AsyncTask<Void, Void, List<String>> {

        private WeakReference<Context> mContextWeakReference;

        public FetchPhotosTask(Context context) {
            mContextWeakReference = new WeakReference<>(context);
        }

        @Override
        protected void onPreExecute() {
            Context context = mContextWeakReference.get();
            if (context != null) {
                ((PhotosActivity) context).mProgressDialog.show();
            }
        }

        @Override
        protected List<String> doInBackground(Void... params) {

            Context context = mContextWeakReference.get();

            if (context != null) {
                //get photos from gallery
                String[] projection = new String[]{
                        MediaStore.Images.Media.DATA,
                };

                Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

                Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);

                if (cursor != null) {
                    List<String> photoUris = new ArrayList<>(cursor.getCount());
                    while (cursor.moveToNext()) {
                        photoUris.add("file://" + cursor.getString(0));
                    }
                    cursor.close();

                    return photoUris;
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(List<String> photoUris) {
            Context context = mContextWeakReference.get();
            if (context != null) {
                ((PhotosActivity) context).mProgressDialog.dismiss();

                if (photoUris != null && photoUris.size() > 0) {
                    ((PhotosActivity) context).mPhotoUris.clear();
                    ((PhotosActivity) context).mPhotoUris.addAll(photoUris);
                    ((PhotosActivity) context).mPhotosAdapter.notifyDataSetChanged();
                }
            }
        }
    }
}

Step 4: 

Here is Adapter’s code

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.util.List;

public class PhotosAdapter extends RecyclerView.Adapter<PhotosAdapter.PhotoViewHolder> {

    private List<String> mPhotoUris;

    public PhotosAdapter(List<String> photoUris) {
        this.mPhotoUris = photoUris;
    }

    @Override
    public PhotosAdapter.PhotoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new PhotoViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_photo_grid, parent, false));
    }

    @Override
    public void onBindViewHolder(PhotosAdapter.PhotoViewHolder holder, int position) {
        Picasso.with(holder.ivPhoto.getContext())
                .load(mPhotoUris.get(position))
                .fit()
                .centerCrop()
                .into(holder.ivPhoto);
    }

    @Override
    public int getItemCount() {
        return mPhotoUris.size();
    }

    public static class PhotoViewHolder extends RecyclerView.ViewHolder {
        ImageView ivPhoto;

        public PhotoViewHolder(View itemView) {
            super(itemView);
            ivPhoto = (ImageView) itemView.findViewById(R.id.iv_photo);
        }
    }
}

Step 5:

Add Grid item layout (for adapter items)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="1dp"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_photo"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:contentDescription="@string/app_name"
        android:scaleType="centerCrop" />

</LinearLayout>

Complete code can be found here

By Ankit on June 29, 2016 | Android | 4 comments
Tags:

Android load two fragments in one FrameLayout

Android load two fragments in one FrameLayout base on button click

Example

activity_main.xml

<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="wrap_content"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="left|top"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="loadFragmentOne"
            android:text="New Button" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="loadFragmentTwo"
            android:text="New Button" />

    </LinearLayout>


    <FrameLayout
        android:id="@+id/mainFrame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="right|top" />

</LinearLayout>

MainActivity.java

package com.example.tutorframelayout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    public void loadFragmentOne(View v) {

        FragmentManager fragmentManager = getSupportFragmentManager();

        Fragment fragmentA = fragmentManager.findFragmentByTag("frag1");

        if (fragmentA == null) {
            fragmentA = new FragmentA();
        }
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.mainFrame, fragmentA, "frag1");
        transaction.commit();
    }

    public void loadFragmentTwo(View v) {

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back

        FragmentManager fragmentManager = getSupportFragmentManager();

        Fragment fragmentB = fragmentManager.findFragmentByTag("frag2");

        if (fragmentB == null) {
            fragmentB = new FragmentB();
        }

        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.mainFrame, fragmentB, "frag2");
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); //setting animation for fragment transaction
        transaction.addToBackStack(null);
        transaction.commit();
    }

}

FragmentA.java

package com.example.tutorframelayout;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FragmentA extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_a,container,false);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //Saving data while orientation changes
        super.onSaveInstanceState(outState);
    }
}

fragment_a.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#df00f7ff">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fragment A" />

</LinearLayout>

FragmentB.java

package com.example.tutorframelayout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentB extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_b,container,false);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //Saving data while orientation changes
        super.onSaveInstanceState(outState);
    }
}

fragment_b.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFBB00">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fragment B" />

</LinearLayout>

OutPut

fragment21

By bm on June 8, 2016 | Android | A comment?

Android Fragment communication

“To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.” :- developer.android.com

Example

activity_main.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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:background="#00BBFF">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:name="com.example.myapp.tutorfragments2.FragmentA"
        android:id="@+id/fragment"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <fragment
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:name="com.example.myapp.tutorfragments2.FragmentB"
        android:id="@+id/fragment2"
        android:layout_below="@+id/fragment"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="79dp" />

</RelativeLayout>

MainActivity.java

package com.example.myapp.tutorfragments2;

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


public class MainActivity extends AppCompatActivity implements Communicator {

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

    @Override
    public void respond(String data) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentB f2 = (FragmentB) manager.findFragmentById(R.id.fragment2);
        f2.changeText(data);
    }
}

FragmentA.java

package com.example.myapp.tutorfragments2;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FragmentA extends Fragment implements View.OnClickListener {

    Button mButton;
    int mCounter = 0;
    Communicator mCommunicator;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //retrieving data from Saved instance when orientation changes
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            mCounter = 0;
        } else {
            mCounter = savedInstanceState.getInt("mCounter", 0);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_a, container, false);
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //creating communicater object with activity context 
        //using this object we can call the respontd method implemented in activity
        mCommunicator = (Communicator) getActivity();

        mButton = (Button) getActivity().findViewById(R.id.button);

        mButton.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.button:
                mCounter++;
                mCommunicator.respond("Counter val : " + mCounter);
                break;
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //Saving data while orientation changes
        super.onSaveInstanceState(outState);
        outState.putInt("mCounter", mCounter);
    }
}

fragment_a.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#FFBB00">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me"
        android:id="@+id/button" />
</LinearLayout>

FragmentB.java

package com.example.myapp.tutorfragments2;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FragmentB extends Fragment {

    TextView mTextView;
    String mData;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_b, container, false);

        if (savedInstanceState == null) {
        } else {
            mData = (String) savedInstanceState.get("text");
            TextView myText = (TextView) view.findViewById(R.id.textView);
            myText.setText(mData);
        }

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mTextView = (TextView) getActivity().findViewById(R.id.textView);
    }

    public void changeText(String data) {
        this.mData = data;
        mTextView.setText(data);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("text", mData);

    }
}

fragment_b.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#99cc00">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView" />
</LinearLayout>

Communicator Interface

package com.example.myapp.tutorfragments2;

public interface Communicator {
    public void respond(String data);
}

 

OutPut

fragment

ref : https://developer.android.com/training/basics/fragments/communicating.html

By bm on | Android | A comment?

Android Fragment example

activity_main.xml

<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:background="#FF00BB"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!-- Static fragment lod here -->
    <fragment
        android:id="@+id/my_fragment"
        android:name="com.example.bikesh.tutorfragments.MyFragments"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_show_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="click Me" />

    <!-- Dynamic fragment lod here (no need to create FrameLayout we can create *any layout)-->
    <FrameLayout
        android:id="@+id/my_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java

package com.example.myapp.tutorfragments;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

        findViewById(R.id.btn_show_fragment).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                MyFragments frag = new MyFragments();
                FragmentManager manager = getSupportFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.add(R.id.my_layout, frag, "view fragment tag");
                transaction.commit();

            }
        });
    }
}

MyFragments.java

package com.example.myapp.tutorfragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by bikesh on 3/12/2015.
 */
public class MyFragments extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);

        return inflater.inflate(R.layout.my_fragments_layout, container, false);
    }
}

my_fragments_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#FFBB00" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text From fragment"
        android:id="@+id/textView" />
</LinearLayout>

 

By bm on | Android | A comment?