Showing posts with label Fragment. Show all posts
Showing posts with label Fragment. Show all posts

Tuesday, March 26, 2013

Google Maps Android API v2 MapFragment tutorial - Implementing Map inside a Fragment

Using MapFragment Android release MapFragment to integrate Map into fragment. using Mapfragment is quite difficult to start but very simple to handle. First of all see Generating Map Key for Google Console project.  Now in Android APP API v2,  include Google play service so you need to add Google Play Service into your project.
    

See screen shot




Step 1) Change your manifest and add permission , Some permission start with you package name. So if you change package of this project than use it. My package name is com.mapfragment. Made changes to your manifest like this

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

<uses-sdk
android:maxSdkVersion="17"
android:minSdkVersion="8"
android:targetSdkVersion="16" />

<permission
android:name="com.mapfragment.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />

<uses-permission android:name="com.mapfragment.permission.MAPS_RECEIVE" />
<!-- Copied from Google Maps Library/AndroidManifest.xml. -->

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!-- External storage for caching. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- My Location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Maps API needs OpenGL ES 2.0. -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-library android:name="com.google.android.maps" />
<!-- You must insert your own Google Maps for Android API v2 key in here. -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"


android:value="yourkey" />


<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>

Step 2) Create two xml inside res/layout folder. One contain FrameLayout ( To embed Fragment inside it) and other contains MapFragment
main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/mainl"
android:layout_height="match_parent" >

</FrameLayout>

Step 3) Do some changes inside your main activity and create one Fragment class to integrate it with in the MainActivity

MainActivity.java
package com.mapfragment;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;

public class MainActivity extends FragmentActivity {
GoogleMap mapView;
com.google.android.gms.maps.Projection projection;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentTransaction mTransaction = getSupportFragmentManager()
.beginTransaction();
SupportMapFragment mFRaFragment = new MapFragmentD();
mTransaction.add(R.id.mainl, mFRaFragment);
mTransaction.commit();

try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}

}
MapFragmentD.Java
package com.mapfragment;

import android.app.Activity;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapFragmentD extends SupportMapFragment {

GoogleMap mapView;

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

@Override
public View onCreateView(LayoutInflater mInflater, ViewGroup arg1,
Bundle arg2) {
return super.onCreateView(mInflater, arg1, arg2);
}

@Override
public void onInflate(Activity arg0, AttributeSet arg1, Bundle arg2) {
super.onInflate(arg0, arg1, arg2);
}

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

mapView = getMap();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.draggable(true);
markerOptions.position(new LatLng(23.231251f, 71.648437f));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
mapView.addMarker(markerOptions);
}
}
Now Lets see How to display Ping on location


        mapView = getMap();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.draggable(true);
markerOptions.position(new LatLng(23.231251f, 71.648437f));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
mapView.addMarker(markerOptions);



Download SourceCode

Sunday, December 16, 2012

Swipe screen navigation using Fragment and View pager in android application

Swiping screens in android application gives a interactive look to application. Using activity its quite difficult as it need some animations. But solution is to use Viewpager (it has default behavior of swipe left right). In ViewPager, attach fragment and its done.

Requirement of this tutorial will be

And Result will be like this video



Let move into depth, This result contain few steps to achieve it

Step 1) Make one fragment activity. This activity xml should contain one ViewPager. Using FragmentPagerAdapter we will add all fragment inside a ViewPager


package com.horizontalscrollviewwithpageindicator;

import java.util.Vector;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.Toast;

import com.fragmentadapter.FragmentAdapter;
import com.fragmentclass.FragmentOne;
import com.fragmentclass.FragmentThree;
import com.fragmentclass.FragmentTwo;

public class FragmentMainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_main);
Vector<Fragment> fragments = new Vector<Fragment>();
FragmentOne fragmentOne = new FragmentOne();
Bundle bundle = new Bundle();
bundle.putString(
"url",
"https://lh6.googleusercontent.com/-jZgveEqb6pg/"
+ "T3R4kXScycI/AAAAAAAAAE0/xQ7CvpfXDzc/s1024/sample_image_01.jpg");
fragmentOne.setArguments(bundle);
fragments.add(fragmentOne);

FragmentTwo fragmenttwo = new FragmentTwo();
bundle.putString(
"url",
"https://lh3.googleusercontent.com/"
+ "-WujkdYfcyZ8/T3R4qrIMGUI/AAAAAAAAAGk/277LIdgvnjg/s1024/sample_image_15.jpg");
fragmenttwo.setArguments(bundle);
fragments.add(fragmenttwo);

FragmentThree fragmenthree = new FragmentThree();
fragmenthree.setArguments(bundle);
fragments.add(fragmenthree);

ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
FragmentAdapter adapter = new FragmentAdapter(
getSupportFragmentManager(), fragments);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);

myPager.setOnPageChangeListener(new OnPageChangeListener() {

@Override
public void onPageSelected(int arg0) {
Toast.makeText(FragmentMainActivity.this,
"Page Selected " + arg0, Toast.LENGTH_LONG).show();
}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}

@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
}

Step 2) Create one FragementPagerAdapter to add data (say Fragment here) to swipe this

package com.fragmentadapter;

import java.util.Vector;

import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.View;
import android.view.ViewGroup;

public class FragmentAdapter extends FragmentPagerAdapter {

FragmentManager mManager;
Vector<Fragment> localFragmentArray;

public FragmentAdapter(FragmentManager fm, Vector<Fragment> loadFragment) {
super(fm);
localFragmentArray = loadFragment;
mManager = fm;
}

@Override
public Fragment getItem(int arg0) {
return localFragmentArray.get(arg0);
}

@Override
public int getCount() {
return localFragmentArray.size();
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
this.notifyDataSetChanged();
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return super.isViewFromObject(arg0, arg1);
}

@Override
public Parcelable saveState() {
return super.saveState();
}

}

Step 3) Create some Fragment Class and add these inside Apdater. Download the code and see how i have added Fragment inside ViewPager


Download Code

Saturday, December 15, 2012

Custom Loader : Loading data using Loader Manager in android asynchronously

Loader is useful while maintaining life cycle of activity and avoiding performing big task again and again. Loader provide a way to keep old data while changing orientation. Every loader has its own unique ID and its created only once. Next time it will use the previous instance.

Loader is discussed at various place but creating your own custom loader is the topic remains to discuss. Let take one case where loader is useful in android

  Suppose application download data from network and show inside a list. suddenly user change phone orientation. Data will start downloading again. To avoid this case, Loader are right thing to use

Loader life cycle include three method

  • public Loader<DataHandler> onCreateLoader(int arg0, Bundle arg1) , called when loader initialize once only
  • public void onLoadFinished(Loader<DataHandler> arg0, DataHandler arg1) every time when applciation interact with Loader. And return data

Note: Here DataHandler is application custom class

  • public void onLoaderReset(Loader<DataHandler> arg0)  to change UI and remove previous view

Now this article will include steps and description to create its own custom loader . It had one list fragment. And after download data using AsyncTaskLoader<DataHandler>, we shows data inside List Fragment

1) One fragment activity is base activity that include on list fragment inside main frame layout
2) Now create List Fragment and initialize the Loader with Loader manager like         

 getActivity().getSupportLoaderManager().initLoader(10, null, this). 

Loader manager has three argument Loader _ID, Bundle data and LoaderManager.LoaderCallbacks<DataHandler>. Now it will force you to override required method of       Loader Manager callback

First will be create loader, here we start one Asynchronous Loader to load data. 


  @Override
public Loader<DataHandler> onCreateLoader(int arg0, Bundle arg1) {
AsynChro asynChro = new AsynChro(ListFragmentExp.this.getActivity());
asynChro.forceLoad();
return asynChro;
}

Loader reset call everytime it interact with loader

@Override
public void onLoaderReset(Loader<DataHandler> arg0) {
mlisListView.setAdapter(null);
}

Loader loaded then it call this method , return with data everytime once it downloaded


       @Override
public void onLoadFinished(Loader<DataHandler> arg0, DataHandler arg1) {
mlisListView.setAdapter(new DataBinder(getActivity(), arg1.getData()));
setListShown(true);
}

3) Once we downloaded data, we just have traditional way to set it inside List Fragment using BaseAdapter

                                   

  

These above images show how loader maintain life cycle of data when you change your orientation . LoaderManager can return any kind of data. Here i have my custom class DataHolder and i am returning data as DataHolder

So Lets go step by step with loader in coding

Activity Class for initiation


package com.loader;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.FrameLayout;

public class MainActivity extends FragmentActivity{
FragmentTransaction mTFragmentTransaction;
FragmentManager mManFragmentManager;
ListFragmentExp mListFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListFragment = new ListFragmentExp();
FrameLayout cursor = (FrameLayout) findViewById(R.id.listFragment);
mManFragmentManager = getSupportFragmentManager();

if (mManFragmentManager.findFragmentByTag("Tag") == null) {
mTFragmentTransaction = mManFragmentManager.beginTransaction();
mTFragmentTransaction.add(cursor.getId(), mListFragment, "Tag");
mTFragmentTransaction.commit();
}
}
}


A List Fragment loading data using LoaderManager and displaying


package com.loader;

import java.util.ArrayList;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;

public class ListFragmentExp extends ListFragment implements
LoaderManager.LoaderCallbacks<DataHandler> {

// This is the Adapter being used to display the list's data.
BaseAdapter mAdapter;
public static ListView mlisListView;
// If non-null, this is the current filter the user has provided.
String mCurFilter;

public static FragmentActivity mAcFragmentActivity;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAcFragmentActivity = getActivity();
// Give some text to display if there is no data. In a real
// application this would come from a resource.
setEmptyText("No phone numbers");

// Create an empty adapter we will use to display the loaded data.
setListAdapter(mAdapter);

// Start out with a progress indicator.
setListShown(false);
mlisListView = getListView();
getActivity().getSupportLoaderManager().initLoader(10, null, this);
}

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

@Override
public Loader<DataHandler> onCreateLoader(int arg0, Bundle arg1) {
AsynChro asynChro = new AsynChro(ListFragmentExp.this.getActivity());
asynChro.forceLoad();
return asynChro;
}

@Override
public void onLoadFinished(Loader<DataHandler> arg0, DataHandler arg1) {
mlisListView.setAdapter(new DataBinder(getActivity(), arg1.getData()));
setListShown(true);
}

@Override
public void onLoaderReset(Loader<DataHandler> arg0) {
mlisListView.setAdapter(null);
}

public static class AsynChro extends AsyncTaskLoader<DataHandler> {

DataHandler mHaDataHandler;

public AsynChro(Context context) {
super(context);
mHaDataHandler = new DataHandler();
}

@Override
public DataHandler loadInBackground() {
ArrayList<String> temp = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
temp.add("Counting-----" + i);
}
try {
synchronized (this) {
wait(5000);
}
} catch (Exception e) {
e.getMessage();
}
mHaDataHandler.setData(temp);
return mHaDataHandler;
}

@Override
public void deliverResult(DataHandler data) {
super.deliverResult(data);
mlisListView.setAdapter(new DataBinder(mAcFragmentActivity, data
.getData()));
}
}

}


And finally one object to save data. I make DataHandler class to save data


package com.loader;

import java.util.ArrayList;

public class DataHandler {

ArrayList<String> mListStrings = new ArrayList<String>();

public void setData(ArrayList<String> temp) {
mListStrings = temp;
}

public ArrayList<String> getData() {
return mListStrings;
}
}
Now Binding all data inside a List Fragment using BaseAdapter


package com.loader;

import java.util.ArrayList;

import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class DataBinder extends BaseAdapter {
ArrayList<String> mLisArrayList;

FragmentActivity mAtcFragmentActivity;

public DataBinder(FragmentActivity mActivity, ArrayList<String> mList) {
mLisArrayList = mList;
mAtcFragmentActivity = mActivity;
}

@Override
public int getCount() {
return mLisArrayList.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

TextView mTextView;
if (convertView == null) {
mTextView = new TextView(mAtcFragmentActivity);

mTextView.setLayoutParams(new ListView.LayoutParams(
LayoutParams.FILL_PARENT, 60));
mTextView.setGravity(Gravity.CENTER_HORIZONTAL
| Gravity.CENTER_VERTICAL);
mTextView.setTextSize(20);
mTextView.setBackgroundColor(Color.GRAY);
mTextView.setTextColor(Color.GREEN);
convertView = mTextView;
} else {
mTextView = (TextView) convertView;
}
mTextView.setText(mLisArrayList.get(position));
return convertView;
}
}

Feel free to download code

Download Source Code

Thursday, September 27, 2012

Action Bar Tab with Fragments example in android

Before getting started with Fragment, See creating Tab with action bar.  Fragment support in android from API level 11 naturally. But if you want to use fragment below this API level then you need to add backward support library, else it will work fine with any library support above API level 10.

These important classes are used while implementing fragment -

  • FragmentManager
  • FragmentTransaction
FragmentTransaction is responsible to add Fragment, Remove Fragment and commit transaction.

If we start from basic step by step- Then first we will get FragmentManager and and will assign it to FragmentTransaction.

                 fragMentTra = getFragmentManager().beginTransaction();  

Now we have object of FragmentTransaction, so we can perform any addition, removal of new Fragment classes.

I have integrated action bar tab with fragment. I have Three classes FragMent1, FragMent2, FragMent3. On changing of Tab every time i added new fragment inside a Relative Layout. So it looks like you are changing activity inside a Tab Layout.

In my main activity, On changing of action bar Tab i added a new Fragment Every time and remove the previous one. So the output of these procedure is look like screen shot given below

                   
               Fragment With ListView
   
Fragment with Grid View

Fragment with Just Simple Image
Now our main concern is to adding  and removing Fragment inside a Relative Layout, You can take other layout also

1:  if (tab.getText().equals("Listing")) {  
2: try {
3: rl.removeAllViews();
4: } catch (Exception e) {
5: }
6: fram1 = new FragMent1();
7: fragMentTra.addToBackStack(null);
8: fragMentTra = getFragmentManager().beginTransaction();
9: fragMentTra.add(rl.getId(), fram1);
10: fragMentTra.commit();
11: } else if (tab.getText().equals("Image")) {
12: try {
13: rl.removeAllViews();
14: } catch (Exception e) {
15: }
16: fram2 = new FragMent2();
17: fragMentTra.addToBackStack(null);
18: fragMentTra = getFragmentManager().beginTransaction();
19: fragMentTra.add(rl.getId(), fram2);
20: fragMentTra.commit();
21: } else if (tab.getText().equals("Details")) {
22: try {
23: rl.removeAllViews();
24: } catch (Exception e) {
25: }
26: fram3 = new FragMent3();
27: fragMentTra.addToBackStack(null);
28: fragMentTra = getFragmentManager().beginTransaction();
29: fragMentTra.add(rl.getId(), fram3);
30: fragMentTra.commit();
31: }
32: }

So this is how we are handling of Fragment. The main benefit is that we have only one activity in complete application. And We separate the complexity of code by using different classes of Fragment.

Every Fragment has one Life Cycle like activity. in oncreateView method we will create the design and will return it. In this method we have inf-later to add one complete layout inside a fragment .

                                                                   Download Source Code

Posting Lama ►
 

Copyright 2013 Tutorials For Newbie: Fragment Template by CB Blogger Template. Powered by Blogger