How to use tabwidget with fragments

This is a simple tutorial on how to use tabs with fragment in android application.

Final output

final output

In this application we are using fragment from android-support-v4.jar,  you are required to add android-support-v4.jar into your app.

1] Create a class lets say “BaseActivity” as we are using fragments to show tabs. BaseActivity class will extends “android.support.v4.app.FragmentActivity” class.

Here is xml file for BaseActivity class

<android.support.v4.app.FragmentTabHost
 android:id="@android:id/tabhost"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" />

<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

</android.support.v4.app.FragmentTabHost>

2] BaseActivity class

In onCreate() method first setup tabhost instance and then add tabs.

mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);

mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator(getResources().getString(R.string.tab_one)), TabOneFrgment.class, null);

mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator(getResources().getString(R.string.tab_two)), TabTwoFrgment.class, null);

Here we are adding tabs in tabhost using addTab method

addTab method takes 3 parameter:

a] TabSpec instance :  you can define tab indicator, can assign a tag for this tab etc.

b] activity which you want to show when user clicks on this tab.

c] bundle instance

  • setIndicator(): here you can set text and or icon which will displayed on tab.

  • You can also add icon with tabs

 Ex : mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator(getResources().getString(R.string.tab_two),

                getResources().getDrawable(R.drawable.ic_launcher)),TabTwoFrgment.class, null);

Tag a tab

By default tabs are shown in the same order as they were added in tabhost.

You can set a tab as current tab  by using setCurrentTabByTag method.

Ex : mTabHost.setCurrentTabByTag("tag2");

You can also show a tab by using tags :

Ex : TabOneFrgment tabOneFrgment = (TabOneFrgment) fragmentManager.findFragmentByTag("tab1");

fragmentTransaction.show(tabOneFrgment);

fragmentTransaction.commit();

How to navigate tabs???

Tab navigation has 2 aspects:

a] create a new fragment (add a fragment)

b] show already added fragment.

It is easy to create a new fragment on tab click but the trickiest part is to retain fragment state while changing tabs.

So in the sample app we are retaining fragment state whenever user changes a tab.

For this you need to add setOnTabChangedListener to the tab host.

Ex : mTabHost.setOnTabChangedListener(new OnTabChangeListener() {.....});

Inside setOnTabChangedListener we need check whether the intended fragment is already created (please refer fragment life cycle).

If fragment is already created  we just need to show that fragment else we will have to create a new fragment and hide current fragment.

 mTabHost.setOnTabChangedListener(new OnTabChangeListener() {

@Override
 public void onTabChanged(String tabId) {

android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();

TabOneFrgment tabOneFrgment = (TabOneFrgment) fragmentManager.findFragmentByTag("tab1");

TabTwoFrgment tabTwoFrgment = (TabTwoFrgment) fragmentManager.findFragmentByTag("tab2");

android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(tabId.equalsIgnoreCase("tab1")){

if(tabOneFrgment != null){

if(tabTwoFrgment != null){

fragmentTransaction.hide(tabTwoFrgment);

}

fragmentTransaction.show(tabOneFrgment);

}

}else{

if(tabTwoFrgment != null){

if(tabOneFrgment != null){

fragmentTransaction.hide(tabOneFrgment);

}

fragmentTransaction.show(tabTwoFrgment);

}

}

fragmentTransaction.commit();

}

});

Download sample project from here.
Happy Coding Happy Learning :)
Advertisements

Tutorial on uploading image on twitter using twitter4j

This tutorial walks you through the steps to post a tweet or a tweet with a image on twitter.

First and foremost you should have a valid twitter app configured correctly to post on twitter.

In case you don’t have an app on twitter, follow the steps below to create a simple twitter app and how to configure it correctly.

Step 1.  Goto https://dev.twitter.com/apps Click on create new application button.

Then you will be presented the following page :

1_twit_create_app

Step 1

Fill in the details of your app.

Make sure you don’t leave the CallBack URL blank. A callback url is the one where your app will be redirected to from twitter; this is a test app so for time being you can specify something like eg: http://www.google.com . If you leave this field blank then your app wont be authorized.

Step 2. Now its time to configure your app. Click on the settings tab. Scroll down to the

Application type section and change access to read and write.

2_twit_settings_app

Step 2

Click on the update settings button at the bottom to reflect the changes. Ideally it takes 10 – 15 seconds for the settings to get updated so be patient.

Step 3. Download twitter4J library from the following url http://twitter4j.org/en/index.html and add it to your libs folder.

Note: The zip contains other additional jars. From these we need only twitter4j-core and

twitter4j-media support jars.

3_twit_libs_eclipse

Step 3

Step 4. Now lets get back to some coding. First you need to add the twitter consumer key and secret key to the Strings xml:

<string name = "twitter_consumer_key">YOUR_CONSUMER_KEY</string>
<string name= "twitter_consumer_secret">YOUR_CONSUMER_SECRET</string>
Step 4

Step 4

In our activity we have two buttons:

  • To post a tweet.

  • To post a tweet with image.

On button click we will check whether the app is already authorized if not we will authorize the app using a custom web view.

We will be using the custom webview to authorize the app so that once the app is authorized, you can finish the webview else you will be stuck with a common issue where the view remains opened even after the app is authorized.

Step 5

Step 5

 

The authorization logic is written in LoginActivity class.

Step 5. How to post a tweet/image on twitter ? Is this that tricky ? Lets have a look at it.

a. Post:

 ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

 configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));

 configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));

 configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));

 configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));

 Configuration configuration = configurationBuilder.build();

 Twitter twitter = new TwitterFactory(configuration).getInstance();

 twitter.updateStatus(message);

b. Post with image:

ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));

configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));

configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));

configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));

Configuration configuration = configurationBuilder.build();

Twitter twitter = new TwitterFactory(configuration).getInstance();

StatusUpdate status = new StatusUpdate(message);

status.setMedia(file); // set the image to be uploaded here.

twitter.updateStatus(status);

As you can see posting is as simple as it can be. Further you can download live and functioning app.

Happy Coding Happy Learning 🙂