How to Use Fragment Layouts in Android

android-293x300-123

Fragment is a concept of UI components-with a new idea for the ability to retain state across configuration changes. As a result, web-pages load comparatively faster because it retains their previous state. Without Fragments components, the normal activity class causes running activities to be stopped, reloaded and re-rendered using the new parameters. A fragment allows building a UI as a series of smaller, reusable graphical elements that can be arranged as needed, based on the device’s capabilities.

Fragment layout in Android is pretty distinct from other platforms. This design was first introduced for the platform in version 3.0 and onwards.

Here are the main concepts about Android fragment layout:

  • Android tabs are most often presented as text compared to icons, because it is difficult to come up with descriptive icons for all the possible navigation option. Text is much better.
  • Android tabs aren’t square buttons.  They mostly contain text
  • Visual style of Android tabs is flat. There should not be any glossy or reflection effects like in html web design.

A Fragment framework works much like an activity.
To implement it in the app we need an independent Java activity class along with a fragment xml layout:

  1. Create a layout XML and an Activity subclass for your activity
  2. Create a layout XML and a Fragment subclass for your fragment
  3. Map the two together in your Activity layout XML (or using FragmentTransaction mostly in Java code)

Example of layout xml for activity

[sourcecode]<?xml version=”1.0″ encoding=”utf-8″?>
<TabHost
xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@android:id/tabhost”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>

<LinearLayout
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>

<FrameLayout
android:id=”@android:id/tabcontent”
android:layout_width=”0dp”
android:layout_height=”0dp”
android:layout_weight=”0″/>

<FrameLayout
android:id=”@+android:id/realtabcontent”
android:layout_width=”fill_parent”
android:layout_height=”0dp”
android:layout_weight=”1″/>

<TabWidget
android:id=”@android:id/tabs”
android:orientation=”horizontal”
android:layout_width=”fill_parent”
android:layout_height=”55dip”
android:layout_weight=”0″/>

</LinearLayout>
</TabHost>
[/sourcecode]

Example of Activity subclass

[sourcecode]package com.myproj;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Stack;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

public class AppMainTabActivity extends FragmentActivity {
/* Your Tab host */
private TabHost mTabHost;

/* A HashMap of stacks, where we use tab identifier as keys..*/
private HashMap<String, Stack<Fragment>> mStacks;

/*Save current tabs identifier in this..*/
private String mCurrentTab;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_layout);
/*
*  Navigation stacks for each tab gets created..
*  tab identifier is used as key to get respective stack for each tab
*/
mStacks = new HashMap<String, Stack<Fragment>>();
mStacks.put(AppConstants.TAB_A, new Stack<Fragment>());
mStacks.put(AppConstants.TAB_B, new Stack<Fragment>());
mStacks.put(AppConstants.TAB_C, new Stack<Fragment>());
mStacks.put(AppConstants.TAB_D, new Stack<Fragment>());
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setOnTabChangedListener(listener);
mTabHost.setup();
initializeTabs();
}

private View createTabView(final int id,String s) {
View view = LayoutInflater.from(this).inflate(R.layout.tabs_icon, null);
ImageView imageView =   (ImageView) view.findViewById(R.id.icon);
imageView.setImageDrawable(getResources().getDrawable(id));
TextView textview= (TextView) view.findViewById(R.id.title);
textview.setText(s);
return view;
}

public void initializeTabs(){
/* Setup your tab icons and content views.. Nothing special in this..*/
TabHost.TabSpec spec    =   mTabHost.newTabSpec(AppConstants.TAB_A);
mTabHost.setCurrentTab(-3);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(R.id.realtabcontent);
}
});
spec.setIndicator(createTabView(R.drawable.cameratab, “Camera”));
mTabHost.addTab(spec);

spec = mTabHost.newTabSpec(AppConstants.TAB_B);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(R.id.realtabcontent);
}
});
spec.setIndicator(createTabView(R.drawable.presettab, “Presets”));
mTabHost.addTab(spec);

//Create a class AppConstants to declare your variables

spec = mTabHost.newTabSpec(AppConstants.TAB_C);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(R.id.realtabcontent);
}
});
spec.setIndicator(createTabView(R.drawable.manualtab, “Manual Entry”));

mTabHost.addTab(spec);

spec = mTabHost.newTabSpec(AppConstants.TAB_D);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(R.id.realtabcontent);
}
});
spec.setIndicator(createTabView(R.drawable.infotab, “Info”));
mTabHost.addTab(spec);
}

/*Comes here when user switch tab, or we do programmatically*/
TabHost.OnTabChangeListener listener    =   new
TabHost.OnTabChangeListener() {
public void onTabChanged(String tabId) {
/*Set current tab..*/
mCurrentTab                     =   tabId;

if(mStacks.get(tabId).size() == 0){
/*
*    First time this tab is selected. So add first fragment of that tab.
*    Dont need animation, so that argument is false.
*    We are adding a new fragment which is not present in stack. So add to stack is true.
*/
if(tabId.equals(AppConstants.TAB_A)){
pushFragments(tabId, new Camera(), false,true);
}else if(tabId.equals(AppConstants.TAB_B)){
pushFragments(tabId, new PresetsActivity(), false,true);
}else if(tabId.equals(AppConstants.TAB_C)){
pushFragments(tabId, new ManualActivity(), false,true);
}else if(tabId.equals(AppConstants.TAB_D)){
pushFragments(tabId, new InfoActivity(), false,true);
}
}else {
/*
*    We are switching tabs, and target tab is already has atleast one fragment.
*    No need of animation, no need of stack pushing. Just show the target fragment
*/
pushFragments(tabId, mStacks.get(tabId).lastElement(), false,false);
}
}
};

/* Might be useful if we want to switch tab programmatically, from
inside any of the fragment.*/
public void setCurrentTab(int val){
mTabHost.setCurrentTab(val);
}

/*
*      To add fragment to a tab.
*  tag             ->  Tab identifier
*  fragment        ->  Fragment to show, in tab identified by tag
*  shouldAnimate   ->  should animate transaction. false when we switch tabs, or adding first fragment to a tab
*                      true when when we are pushing more fragment into navigation stack.
*  shouldAdd       ->  Should add to fragment navigation stack (mStacks.get(tag)). false when we are switching tabs (except for the first time)
*                      true in all other cases.
*/
public void pushFragments(String tag, Fragment fragment,boolean shouldAnimate, boolean shouldAdd){
if(shouldAdd)
mStacks.get(tag).push(fragment);
FragmentManager   manager         =   getSupportFragmentManager();
FragmentTransaction ft            =   manager.beginTransaction();
if(shouldAnimate)
ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
ft.replace(R.id.realtabcontent, fragment);
ft.commit();
}

public void popFragments(){
/*
*    Select the second last fragment in current tab’s stack..
*    which will be shown after the fragment transaction given below
*/
Fragment fragment             =   mStacks.get(mCurrentTab).elementAt(mStacks.get(mCurrentTab).size() – 2);

/*pop current fragment from stack.. */
mStacks.get(mCurrentTab).pop();

/* We have the target fragment in hand.. Just show it.. Show a standard navigation animation*/
FragmentManager   manager         =   getSupportFragmentManager();
FragmentTransaction ft            =   manager.beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
ft.replace(R.id.realtabcontent, fragment);
ft.commit();
}

@SuppressLint(“NewApi”)
@Override
public void onBackPressed() {
if(((BaseFragment)mStacks.get(mCurrentTab).lastElement()).onBackPressed() == false){
/*
* top fragment in current tab doesn’t handles back press, we can do our thing, which is
*
* if current tab has only one fragment in stack, ie first fragment is showing for this tab.
*        finish the activity
* else
*        pop to previous fragment in stack for the same tab
*
*/
if(mStacks.get(mCurrentTab).size() == 1){
super.onBackPressed();  // or call finish..
}else{
popFragments();
}
}else{
//do nothing.. fragment already handled back button press.
}
}

/*
*   Imagine if you wanted to get an image selected using ImagePicker intent to the fragment. Ofcourse I could have created a public function
*  in that fragment, and called it from the activity. But couldn’t resist myself.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

mStacks.get(mCurrentTab).lastElement().onActivityResult(requestCode, resultCode, data);
}
}
[/sourcecode]

Example of Fragment subclass

[sourcecode]package com.myproj;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;

public class BaseFragment extends Fragment {
public AppMainTabActivity mActivity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

mActivity    = (AppMainTabActivity) this.getActivity();
}

public boolean onBackPressed(){
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data){

}
}
[/sourcecode]

Fragment layout in Android is pretty distinct from other platforms. This design was first introduced for the platform in version 3.0 and onwards.

Here are the main concepts about Android fragment layout:

  1. Android tabs are most often presented as text compared to icons. Because, it is difficult to come up with descriptive icons for all the possible navigation option. Text is much better.
  2. Android tabs aren’t square buttons.  They mostly contain text
  3. Visual style of Android tabs is flat. There should not be any glossy or reflection effects like in html web design.

A fragment must always be embedded in an activity and the fragment’s lifecycle is directly affected by the parent activity’s lifecycle. When we add a fragment as a part of an activity layout, it lives in ViewGroup inside the activity’s view hierarchy and the fragment defines its own view layout. We can insert a fragment into the activity layout by declaring the fragment in the activity’s layout file, as a <fragment> element, or from the application code by adding it to an existing ViewGroup.
To animate the transition between fragments or to animate the process of showing or hiding a fragment the Fragment Manager API can be used and create a Fragment Transaction.
Within each Fragment Transaction we can specify in and out animations that will be used for show and hide respectively (or both when replace is used).

Benefits:

Fragments are useful in following cases:

  • If we split up views on some devices/orientations and show them in two activities and show all the content in one on other devices. That would be a use case if you go on a tablet or maybe even in landscape mode on a phone: e.g. you show the list of items and the details on one screen. On a phone or in portrait mode you just show one part.
  • Another use case is reusable views. So if we have some views that are visible on different activities and also perform some actions we could put this behavior into a fragment and then reuse it.
  • Animated effects can availed when dynamically adding and removing fragments from the screen
  • Integration with the action bar for tabs, as a replacement for TabHost
  • Integration with the action bar for “list”-based navigation (really a Spinner in the action bar, toggling between different fragments)

See Also: Webview Layouts usages in Android

If you have thoughts about or experiences with Android fragments, share them with us. We’d love to hear from you.

Expected devices with Android 4.2 upgrades

android_jelly_been_123

Google’s Android 4.2 was released last October, which introduced numerous new features and enhancement for Jelly Bean OS platform. It included lock screen widgets and photo Sphere as well as new quick settings panel and screensaver function. For tablets, the upgrade included phone like user-interfaces and multi-user support

It has been nearly a year since the release of Samsung Galaxy Tab and apparently Samsung is planning to release an update to Android 4.1.2 first and then the final OTA Update with Android 4.2.2 Jelly Bean OS for the tablet. This will be the last official update from Samsung and hence further the users will have to rely on the Android development community for custom ROMs based on Android 5.0. The news first surfaced at ‘SamMobile’ and it seems like Samsung has fixed issues with Android 4.2.2 and Exynos CPU. Samsung will probably abandon updates for its former flagship tablet after the release of Jelly Bean 4.2.2 firmware update. These update i.e. Android 4.2.1 and 4.2.2 is expected to be available till September 2013. It is also rumored that Samsung devices with dual-core CPU will also receive Jelly Bean 4.2.2 updates.

There were other Galaxy Tab devices that are tested on Jelly Bean ROMs and its official release is expected by April 2013. The Jelly Bean OS is now tested on Galaxy Tab 10.1 GT 7500, Galaxy Tab GT 7300, Galaxy Tab 7.7 P6800 and the Galaxy Tab Plus P6200. These updates are yet to happen until Samsung decides to officially announce the release dates of OTA updates for Jelly Bean 4.2.2.

For Google’s nexus devices the upgrades are often early and directly from Google. Even carrier connected devices like the Verizon Galaxy Nexus are finally catching up, which generally experienced delays in update because of carrier interference. Asus gave Android 4.2 update to its Transformer Pad TF300 at the beginning of March and has said to release updates for Transformer Pad Infinity, MeMO Pad Smart and MeMO Pad, later this year. Sony has confirmed that it would release Android 4.2 upgrades for Xperia Z and Xperia Tablet Z devices. Motorola has also promised it would upgrade their Android OS for Motorola’s International Razr D1 and D3, but haven’t provided any definite timeline for the process.

Mobile device manufacturers are now willing to focus their Android Application Development efforts on Android 4.1 upgrade before heading to 4.2, because 4.2 is relatively a minor step from 4.1. Some companies are even considering to skip directly to the next major Android release i.e. Android Key Lime Pie, which is expected to be announced at Google’s I/O conference in May .

SwiftKey has unveiled its version 4 keyboard app for Android devices

androidimg

To be completely honest, most android users are not satisfied with the android’s default keyboard. It can be fiddly for some users, who write languages other than English on a daily basis. After all it doesn’t cater to everyone’s typing style either. However “SwiftKey” has always proved to be the best keyboard app alternative for the android platform. This time the developers at SwiftKey have launched its version 4 for the android devices

One of the best features of this keyboard is its ability to gradually learn the user’s typing preferences. It studies how a user writes over time and generates predictive texts for him, which is surprisingly accurate and better than any other applications. SwiftKey has also included its swipe like feature called the SwiftKey Flow which lets the user type sentences without lifting finger from the mobile screen. SwiftKey now supports over 60 international languages.

Here are some of the most notable features in version 4 release:

  • SwiftKey Flow is a gesture typing feature that facilitates the users to write sentences simply by gliding over the keys. It also adds auto-correction ability as-well-as predicts the possible next words while typing.
  • It can also be blend with tap inputs and switching mid-word.
  • If the predicted word is correct then it can be inserted by simply lifting the finger off.
  • Flow through space lets the user type a complete sentence in one motion without lifting the finger, to give spaces between the words.
  • It supports word prediction for over 60 languages like Javanese, Sundanese, and Vietnamese etc with both auto-correction and word prediction abilities.
  • Easier correction and auto adaptability to users typing style.

According to reports Android application development with SwiftKey’s SDK now supports iOS, JVM, Linux, Mac OS-X, Windows, and C++ etc. SwiftKey had released its Flow feature in the last October and its Beta version was tested with a community of million users.  Being awarded numerous times for its keyboard application, it surely is one of the best android keyboard apps, plus it comes with a reasonable price.

Android 4.2.2 brings minor updates for the Nexus users with improvements in Bluetooth audio issue

androidimg

Android’s latest 4.2.2 update is already released and beginning to roll out for its Nexus devices. This update will late be availed to other Mobile devices too. Since its last update i.e. Android 4.2.1 during the late November, 4.2.2 appears to have minor fixes only.

Android 4.2.2 update has primarily resolved the issue of audio streaming over Bluetooth that used to skip during the operation. Reddit user WeeManFoo quoted “Bluetooth streaming works better (compared to 4.2.1) but it’s not perfect” and mentioned that for other notable fixes or features to 4.2.2, users might have to wait for an official changelog.

WeeManFoo also referred that his Galaxy Nexus still gets disconnected from Bluetooth speakers when switching from Wi-Fi to a 3G data connection. So, it appears that there is still some work to be done by the android developers.

Google has also modified the new ‘Quick Settings panel’ introduced in Android 4.2.2. The Wi-Fi and Bluetooth icons in the panel can now be turned OFF and ON by long-pressing the icons, instead of browsing to their respective settings panels.

Google has also introduced a notification sound for wireless charging and has changed the notification sound that indicates that the phone or tablet’s battery is running low.

None of these are major changes, but they sure bring the refinements that we expect from a minor update. Android 4.2.2 continues to roll out to Galaxy Nexus, Nexus 7, and Nexus 10 devices however Nexus 4 users will have to wait for now.

At Andolasoft we develop unique android mobile applications for individuals and from start-ups to established companies. We’ve an expertise team of android app developers who design the most innovative apps for all android devices.

Android 4.2.2 is set for release this month!

androidimg

Google is constantly working to roll out its Jelly Bean update in the form of Android 4.2.2 in the end of this month. It is likely to be a minor update that will fix the prevalent bugs and to enhance the performance speed of the Jelly Bean OS. It is also expected to patch the Bluetooth streaming issue in Nexus 7 devices.

Some reports suggested that, Google is already testing the 4.2.2 update on all Nexus devices like the Nexus 4, Nexus7 and Nexus 10. According to the website, Google claims to release it to the consumers by mid-February. These rumors have been there for quite some time since the last couple of months but reporters have already spotted some Google Nexus 4 devices in Malaysia and Brazil that were running Android 4.2.2.

Rumors have it, that Google will be releasing its next Android version 5.0 in-between April and June of this year. This update may also be called as ‘Key Lime Pie’. Google has announced that its next developer conference will take place during May 15 to May 17 of 2013, where they might introduce new android applications for version 5.0. Finally, as only 1.2 % of Android devices run 4.2 Jelly Bean versions, only a few users would be benefited from this update.

At Andolasoft we develop the most intriguing android applications for our customers. We have a pool of expertise android developers to provide innovative solutions for all versions of android operating software.

Technology to run Android on Windows without emulation

android31There are numerous operating systems available in the market such as windows, MacOSX, Linux etc. But there is no way to run Android OS natively on a computer. In order to carve this problem, advancements have been made to run Android on a windows system without a simulator. It will enable the Android operating system to run on ‘Windows’ kernel instead of its usual ‘Linux’ kernel. This system will detach the need of an emulation layer, therefore making the android OS performance ultra-fast.

Some of the first hand users said that this wasn’t the first application to run Android on windows but its ability to negate the use of emulation layer, is what makes it welcoming.

The system is currently believed to be working with Android 4.0 and could be installed on Windows 8, Windows 7 and Windows Vista. But in order to set-up the application, it would require a little android application development familiarity, more than the basic knowledge of using an android Smartphone. Once installed, it can be used like a native android OS on a computer. It will be enabled to run all kinds of android applications including the 3D games. This technology will bring new possibilities to run simulated environment on a different OS, without any hindrances.

At Andolasoft we develop the most intriguing android mobile applications for individuals and from start-ups to established companies. We’ve an expertise team of android application developers developing the most innovative apps for all android devices.