How to show an AlertDialog from any Activity in my application.

Hello Friends,

I hope my previous posts might have helped you.This time I want to do experiment with Service,AlertDialog and Notifications and BroadcastReciever.
As you all know “A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application.”

To know more about service you can see Service.

And Broadcast receivers: A broadcast receiver is a component that responds to system-wide broadcast announcements.

And for notifying user for anything there are Toast,Status Bar Notification and Dialogs.Like you have some process is running in background and you want to notify user about its completion so you can use one of these.

    * A Toast Notification, for brief messages that come from the background.
    * A Dialog Notification, for Activity-related notifications.
    * A Status Bar Notification, for persistent reminders that come from the background and request the user’s response.

You can learn more from here about Notification from here.

Now what is today’s experiment is to use all these together in an one more innovative way.This came to my mind when I was facing a problem during one of my project.

In my project I was using a Service and in that service I was checking messages coming from a server.What I wanted is whenever a message comes I should check it and if it is worth of then notify the user.And for project it was mandatory for me that a user must see the message.So in this case Toast notification was not proper way because Toast notification pops up for some time only and disappears so there are chances my user miss the message (and that I don’t want).

So for this I used Dialog (or specifically AlertDialog).By using AlertDialog you can force user to see its message and also there you can add buttons.A very good example that nobody want in there app is ForceClose.

But there is still a problem with AlertDialog.Dialogs are specific to Activities so if you have used Dialog for one activity and your user is on another activity,So again user can miss your message.

So for solution of these there is a third kind of notifications ie called “Status Bar Notification”.

A status bar notification adds an icon to the system’s status bar (with an optional ticker-text message) and an expanded message in the “Notifications” window.
By expanding it user can see the message and also you can set Intent.
When the user selects the expanded message, Android fires an Intent that is defined by the notification (usually to launch an Activity).

You can also configure the notification to alert the user with a sound, a vibration, and flashing lights on the device.
This is a good way of notifying user when you are using Service.

After all this I thought I have found solutions for my problem and definitely I had.But then from where it is “innovative”, it is a usual way of using it.

So I thoght how can I make it innovative and then I tried to solve the problem with Dialogs.

“Dialogs are specific to Activities so if you have used Dialog for one activity and your user is on another activity then user can miss your message.”

Then I decided that I will show the AlertDialog along with message on every activity in my application and if my application is minimized and another application is runninng in foreground then I will show Status Bar Notification.

For this I thought I will show dialog from my Service itself but “You cannot display a dialog from a Service or BroadcastReceiver”.

Now I had to do something else.So lets try it..

First of all I created a Service which does my main task to get message from server.But in this example I am not interacting with server instead that I am using an counter and incrementing it.on incrementing counter I am checking its value in service(in background) and whenever it meets my condition I notify user with a message.

TestService.java

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.widget.Toast;

public class TestService extends Service
{
    final static String TAG = “TestService”;
    private final Handler handler = new Handler();
    public static final String BROADCAST_ACTION = “com.ab1209.broadcast.testservice”;
    public static int COUNTER = 0;
    Intent intent;
    Ringtone ringtone;

    @Override
    public IBinder onBind(Intent arg0)
    {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate()
    {
        // TODO Auto-generated method stub
        super.onCreate();
//        alertSound();
        intent = new Intent(BROADCAST_ACTION);
    }

    @Override
    public void onStart(Intent intent, int startId)
    {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Toast.makeText(getApplicationContext(), “Serivce Started”, Toast.LENGTH_SHORT).show();
        
        handler.removeCallbacks(sendAlertRunnable);
        handler.postDelayed(sendAlertRunnable, 1000);
    }

    private Runnable sendAlertRunnable = new Runnable()
    {
        @Override
        public void run()
        {
            // TODO Auto-generated method stub
            new TraceTask().execute();
            handler.postDelayed(this, 1000);
        }
    };

    public void onDestroy()
    {
        Toast.makeText(getApplicationContext(), “Serivce Stopped”, Toast.LENGTH_SHORT).show();
        handler.removeCallbacks(sendAlertRunnable);
        super.onDestroy();
    };

    private class TraceTask extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute()
        {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String… params)
        {
            // TODO Auto-generated method stub
            SystemClock.sleep(1000);
            COUNTER++;
            return null;
        }

        @Override
        protected void onPostExecute(String result)
        {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            if (COUNTER % 5 == 0)
                sendAlert();
            if (COUNTER > 50)
            {
                stopSelf();
                sendAlert();
            }
        }
    }

    void sendAlert()
    {
        if (MainActivity.STATE == MainActivity.RUNNING)
        {
            String message = “Message from Broadcast ” + COUNTER;
            if (COUNTER > 50)
                message = “Service Stopped”;

            intent.putExtra(“MESSAGE”, message);
//            ringtone.play();
            
            sendBroadcast(intent);
        } else if (MainActivity.STATE == MainActivity.PAUSED)
        {
            showNotification();
        }
    }

    void showNotification()
    {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher, “TestService Notification”, 1000);

        Context context = getApplicationContext();
        Intent intent = new Intent(this, Activity2.class);

        String message = “Message from Notification ” + COUNTER;
        intent.putExtra(“MESSAGE”, message);
        if (COUNTER > 50)
            message = “Service Stopped”;

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setLatestEventInfo(context, “Test Service”, message, pendingIntent);
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.defaults |= Notification.DEFAULT_SOUND;
        
        notificationManager.notify(R.drawable.ic_launcher, notification);
    }
    
    void alertSound()
    {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
    }

}

For incrementing and checking counter value I am using AsyncTask and its doInBackground() method (Where I interct with server).
Method sendAlert() is for notifying user.The interesting thing I have done here is if my Activity is paused (ie in background) then I will show a Status Bar Notification and if it is on foreground so I will show a AlertDialog.

For this I have used three static variables STATE,PAUSED and RUNNING.So whenver my Activity is paused I set STATE = PAUSED and if on foreground I set STATE = RUNNING.
By checking STATE value I decide when to show AlertDialog or Status Bar Notification.

for showing AlertDialog I have used Broadcasting intent using

public static final String BROADCAST_ACTION = “com.ab1209.broadcast.testservice”;
Intent intent = new Intent(BROADCAST_ACTION);
 
After completion of one AsyncTask I am starting it again by
private Runnable sendAlertRunnable = new Runnable()
    {
        @Override
        public void run()
        {
            // TODO Auto-generated method stub
            new TraceTask().execute();
            handler.postDelayed(this, 1000);
        }
    };

One more thing if you want to notify user with sound and vibration so in Status Bar Notification you can do it easily using

notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;

but adding sound for AlertDialog you can try this

void alertSound()
    {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
    }

and use
ringtone.play();
and then send message using
sendBroadcast(intent);

On testing on emulator you may get an NullPointerException on ringtone.play(); so first you will have to set an ringtone to you emulator also.
for this you can check http://yenliangl.blogspot.in/2009/12/no-ringtones-in-android-emulator.html.

You must add Service in your AndoroidManifest.xml and also VIBRATE permission if you want to alert with vibration also.

Now its time for my Activity from where I will start Service, show AlertDialog when recieving broadcasts.

MainActivity.java

package com.test.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity
{
    Intent intentService;
    Button btn;

    public final static int RUNNING = 1209;
    public final static int PAUSED = 9021;
    public static int STATE = RUNNING;

    AlertDialog alertDialog;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Toast.makeText(getApplicationContext(), “onCreate”, Toast.LENGTH_SHORT).show();
        initParameters();
        getNotificationIntent();
    }

    void getNotificationIntent()
    {
        String message = getIntent().getStringExtra(“MESSAGE”);
        if(message!=null)
        showAlertDialog(message);
    }
    void initParameters()
    {
        prepareAlertDialog();
        intentService = new Intent(this, TestService.class);
        registerReceiver(broadcastReceiverTestService, new IntentFilter(TestService.BROADCAST_ACTION));
    }

    private BroadcastReceiver broadcastReceiverTestService = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            String message = intent.getStringExtra(“MESSAGE”);
            showAlertDialog(message);
        }
    };

    void prepareAlertDialog()
    {
        alertDialog = new AlertDialog.Builder(MainActivity.this).create();
        alertDialog.setButton(“OK”, new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
            }
        });
    }
    
    void showAlertDialog(String message)
    {
        alertDialog.setMessage(message);
        alertDialog.show();
    }

    @Override
    protected void onPause()
    {
        // TODO Auto-generated method stub
        super.onPause();
        STATE = PAUSED;
    }

    @Override
    protected void onResume()
    {
        // TODO Auto-generated method stub
        super.onResume();
        STATE = RUNNING;
    }

}

In MainActivity I have used three static variables STATE,PAUSED and RUNNING and in Service I check this variable and decide how to notify user (by AlertDialog or Status Bar Notification).
I am changing variable STATE value in onPause() and onResume() methods.

@Override
    protected void onPause()
    {
        // TODO Auto-generated method stub
        super.onPause();
        STATE = PAUSED;
    }

    @Override
    protected void onResume()
    {
        // TODO Auto-generated method stub
        super.onResume();
        STATE = RUNNING;
    }

A my AlertDialog is only related to MainActivity only so if I will switch to other Activity then I want be able to see AlertDialog(Althogh I will be able to see Status Bar Notification).But as “innovative” way I have to show AlertDialog at every Activity of my app and that will not happen in this case.

For implementing this what I have done is
First thing I haven’t use setContentView() ie there is no View set to this MainActivity and second I have created two more activites (you can create as many as you want) Activity1 and Activity2.
These two activity Activity1 and Activity2 extends my MainActivity and by extending this they have got all the properties of it and of course with their own.So now both activities can start and stop Service from MainActivity and show AlertDialog.

Here are my two sub activities
 
Activity1.java

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class Activity1 extends MainActivity implements OnClickListener
{
    Button btn;
    Button btnStartService;
    Button btnStopService;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity1);
        initViews();
    }

    void initViews()
    {
        btnStartService = (Button) findViewById(R.id.button_start_service);
        btnStartService.setOnClickListener(this);

        btnStopService = (Button) findViewById(R.id.button_stop_service);
        btnStopService.setVisibility(LinearLayout.GONE);
        btnStopService.setOnClickListener(this);

        btn = (Button) findViewById(R.id.button_act1);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub

        switch (v.getId())
        {
        case R.id.button_act1:
            Intent intent = new Intent(this, Activity2.class);
            startActivity(intent);
            break;

        case R.id.button_start_service:
            startService(intentService);

            btnStopService.setVisibility(LinearLayout.VISIBLE);
            btnStartService.setVisibility(LinearLayout.GONE);
            break;
        case R.id.button_stop_service:
            stopService(intentService);

            btnStartService.setVisibility(LinearLayout.VISIBLE);
            btnStopService.setVisibility(LinearLayout.GONE);
            break;
        }

    }
}

Layout for Activity1 is activity1.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
    android:layout_width=”fill_parent”
    android:layout_height=”fill_parent”
    android:orientation=”vertical” >

    <Button
        android:id=”@+id/button_start_service”
        android:layout_width=”fill_parent”
        android:layout_height=”wrap_content”
        android:text=”Start Service” />

    <Button
        android:id=”@+id/button_stop_service”
        android:layout_width=”fill_parent”
        android:layout_height=”wrap_content”
        android:text=”Stop Service” />

    <Button
        android:id=”@+id/button_act1″
        android:layout_width=”fill_parent”
        android:layout_height=”wrap_content”
        android:text=”To Activity 2″ />

    <TextView
        android:layout_width=”fill_parent”
        android:layout_height=”fill_parent”
        android:gravity=”center”
        android:text=”ACTIVITY 1″
        android:textColor=”#FFF”
        android:textSize=”20dip”
        android:textStyle=”bold” />

</LinearLayout>

and Activity2.java

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Activity2 extends MainActivity implements OnClickListener
{
    Button btn;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2);
        btn = (Button) findViewById(R.id.button_act2);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        Intent intent = new Intent(this, Activity1.class);
        startActivity(intent);
    }
}

Layout for Activity1 is activity2.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
    android:layout_width=”fill_parent”
    android:layout_height=”fill_parent”
    android:orientation=”vertical” >

    <Button
        android:id=”@+id/button_act2″
        android:layout_width=”fill_parent”
        android:layout_height=”wrap_content”
        android:text=”To Activity 1″ />

    <TextView
        android:layout_width=”fill_parent”
        android:layout_height=”fill_parent”
        android:gravity=”center”
        android:text=”ACTIVITY 2″
        android:textColor=”#FFF”
        android:textSize=”20dip”
        android:textStyle=”bold” />

</LinearLayout>
 

My first activity is Activity1 and I can start and stop Service from here and also can switch from other activity Activity2.So if you will switch to any activity you will see an message through same AlertDialog and if your application is in background you will recieve Status Bar Notification.

And this is how I solved my problem in innovative way.Hope you will try and let me know about your views about it.

For getting basic idea of how to use Service and BroadcastReceiver together you can check here.

So that’s all for today from my side.Soon I will be back with something more interesting thing.

Thanks

 

 

 

How to create EditText with cross(x) button at end of it?

Hello Friends,
I am back again with one more Android experiment. This time it is EditText.EditText is a view which is used so frequently in Android application,specially in applications which has forms which allow user to fill information of any kind.

When you have filled any form you must have a faced an problem (specially on mobile devices) ie. deleting the text written in EditText.You use a delete key on keyboard to delete the text.Sometime it becomes so irritating to delete the text by pressing the delete key.

So to get rid off from this irritation I have created my own custom EditText ie. ClearableEditText.This customized view contains a Button inside the EditText itself. So just on pressing this Button only once you can clear all the text written within the EditText.

I have also added one more interesting feature to ClearableEditText view.Your Clear button will be visible only when it will have text written in it otherwise it will be invisible.Isn’t it Intersting ?

So here my code goes…
First XML code for customized view.

clearable_edit_text.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
>

<EditText
android:id=”@+id/clearable_edit”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:paddingRight=”35dip”
/>
<Button
android:id=”@+id/clearable_button_clear”
android:layout_width=”30dip”
android:layout_height=”30dip”
android:layout_alignParentRight=”true”
android:background=”@drawable/image_clear”
android:layout_centerVertical=”true”
android:layout_marginRight=”5dip”/>

</RelativeLayout>

For creating any custom view we must extend any existing view class.As I am creating a compound view (ie. Combination of many views) I need to extend a view that can contain many child views in it. So I have used RelativeLayout for it.
In my customized view class ie ClearableEditText I have extended RelativeLayout and override its constructors.In its constructor I have inflated a layout resource which I have created (In our case clearable_edit_text). Then I have taken refereneces to each of the view it contains (ie. a EditText and a Button).

For its special features I have created two methods.

* First for deleting text written within the EditText.
clearText();
This method simply uses setText() method of EditText view to set the text to blank (“”).

* Second method the most interesting one is showHideClearButton();
This method adds a TextChangedListener to EditText.TextChangedListener takes a TextWatcher as a parameter so we can monitor the text being written in EditText.So in its  onTextChanged() method we have used our logic.

package com.ab1209.wordpress;

import com.ab1209.wordpress.R;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

public class ClearableEditText extends RelativeLayout
{
LayoutInflater inflater = null;
EditText edit_text;
Button btn_clear;

public ClearableEditText(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
initViews();
}

public ClearableEditText(Context context, AttributeSet attrs)
{
super(context, attrs);
// TODO Auto-generated constructor stub
initViews();

}

public ClearableEditText(Context context)
{
super(context);
// TODO Auto-generated constructor stub
initViews();
}

void initViews()
{
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.clearable_edit_text, this, true);
edit_text = (EditText) findViewById(R.id.clearable_edit);
btn_clear = (Button) findViewById(R.id.clearable_button_clear);
btn_clear.setVisibility(RelativeLayout.INVISIBLE);
clearText();
showHideClearButton();
}

void clearText()
{
btn_clear.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
edit_text.setText(“”);
}
});
}

void showHideClearButton()
{
edit_text.addTextChangedListener(new TextWatcher()
{

@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// TODO Auto-generated method stub
if (s.length() > 0)
btn_clear.setVisibility(RelativeLayout.VISIBLE);
else
btn_clear.setVisibility(RelativeLayout.INVISIBLE);
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s)
{
// TODO Auto-generated method stub

}
});
}

public Editable getText()
{
Editable text = edit_text.getText();
return text;
}
}

So now our Customized view ClearableEditText is ready now we can use it wherever we need it.

like

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >

<com.and.ab1209.ClearableEditText
android:id=”@+id/edit_text_clearable”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />

</LinearLayout>

I hope you will like it.

Thanks

ab1209

How to make simultaneous scrollable views in Android.

Hello All I am back with one more innovative way that can be used in Android.
This time I am targeting ScrollView.
There may be situation where you want simultaneous scrolling of two Views.I have tried it with more exciting way. I hope you will like this way.

Here I am using four section
1.First it is static view no scrolling is allowed here.
2.Second it can be scrolled horizontal only.
3.Third it can be scrolled vertical only.
4.Fourth it can be scrolled both vertically and horizontaly.

The interesting thing is that when second section is scrolled horizontaly so simultaneously fourth section also scrolled in horizontal direction & vice versa and if third section is scrolled vertically so fourth section also scrolls in vertical direction & vice versa.

The XML code is as follows.

scrolltest.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:orientation=”vertical” android:layout_width=”fill_parent”
android:layout_height=”200dip”>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”wrap_content”>
<LinearLayout android:layout_width=”100dip”
android:layout_height=”100dip” android:background=”#FABCDE”>
<TextView android:id=”@+id/textView1″ android:text=”FIXED”
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/blue” android:textSize=”20dip”
android:gravity=”center” />
</LinearLayout>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”100dip”>
<com.overflow.ab1209.etc.ObservableHorizontalScrollView
android:layout_width=”fill_parent” android:layout_height=”fill_parent”
android:id=”@+id/scroll_horizontal_only” android:background=”#AAACDE”>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>

<TextView android:id=”@+id/textView1″ android:text=”Horizontal Only    “
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/blue” android:gravity=”center_vertical” />
<TextView android:id=”@+id/textView1″ android:text=”Horizontal Only    “
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/blue” android:gravity=”center_vertical” />
<TextView android:id=”@+id/textView1″ android:text=”Horizontal Only    “
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/blue” android:gravity=”center_vertical” />
<TextView android:id=”@+id/textView1″ android:text=”Horizontal Only    “
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/blue” android:gravity=”center_vertical” />
<TextView android:id=”@+id/textView1″ android:text=”Horizontal Only    “
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/blue” android:gravity=”center_vertical” />
<TextView android:id=”@+id/textView1″ android:text=”Horizontal Only    “
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/blue” android:gravity=”center_vertical” />
<TextView android:id=”@+id/textView1″ android:text=”Horizontal Only    “
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/blue” android:gravity=”center_vertical” />
<TextView android:id=”@+id/textView1″ android:text=”Horizontal Only    “
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/blue” android:gravity=”center_vertical” />

</LinearLayout>
</com.overflow.ab1209.etc.ObservableHorizontalScrollView>
</LinearLayout>

</LinearLayout>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<LinearLayout android:layout_width=”100dip”
android:layout_height=”fill_parent” android:background=”#FABCDE”>
<com.overflow.ab1209.etc.ObservableScrollView
android:layout_width=”fill_parent” android:layout_height=”fill_parent”
android:id=”@+id/scroll_vertical_only” android:background=”#CCCCDE”>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”fill_parent” android:orientation=”vertical”>
<TextView android:id=”@+id/textView1″ android:text=”Vertical Only”
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/red” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Only”
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/red” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Only”
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/red” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Only”
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/red” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Only”
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/red” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Only”
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/red” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Only”
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/red” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Only”
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/red” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Only”
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:textColor=”@color/red” />

</LinearLayout>
</com.overflow.ab1209.etc.ObservableScrollView>
</LinearLayout>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<com.overflow.ab1209.etc.ObservableScrollView
android:layout_width=”fill_parent” android:layout_height=”fill_parent”
android:id=”@+id/scroll_vertical_from_both”>
<com.overflow.ab1209.etc.ObservableHorizontalScrollView
android:layout_width=”fill_parent” android:layout_height=”fill_parent”
android:id=”@+id/scroll_horizontal_from_both” android:background=”#FFFFFE”>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”fill_parent” android:orientation=”vertical”>

<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:orientation=”horizontal”>
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
</LinearLayout>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:orientation=”horizontal”>
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
</LinearLayout>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:orientation=”horizontal”>
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
</LinearLayout>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:orientation=”horizontal”>
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
</LinearLayout>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:orientation=”horizontal”>
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
</LinearLayout>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:orientation=”horizontal”>
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
</LinearLayout>
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:orientation=”horizontal”>
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
<TextView android:id=”@+id/textView1″ android:text=”Vertical Horizontal both  “
android:layout_width=”wrap_content” android:layout_height=”wrap_content” />
</LinearLayout>

</LinearLayout>
</com.overflow.ab1209.etc.ObservableHorizontalScrollView>
</com.overflow.ab1209.etc.ObservableScrollView>
</LinearLayout>

</LinearLayout>
</LinearLayout>

For this I have created two custom scrollable view class that extends HorizontalScrollView for horizontal scrolling & another extends ScrollView for vertical scrolling.
And also I have created a Interface which contains two abstract methods which monitor scrolling functionality ,one for horizontal another one for vertical.

Java Code is..

1.) ObservableScrollView.java

package com.ab1209.etc;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

public class ObservableScrollView extends ScrollView
{

private ScrollViewListener scrollViewListener = null;

public ObservableScrollView(Context context)
{
super(context);
}

public ObservableScrollView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}

public ObservableScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}

public void setScrollViewListener(ScrollViewListener scrollViewListener)
{
this.scrollViewListener = scrollViewListener;
}

@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy)
{
super.onScrollChanged(x, y, oldx, oldy);
if (scrollViewListener != null)
{
scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
}
}

}

2.) ObservableHorizontalScrollView.java

package com.ab1209.etc;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;

public class ObservableHorizontalScrollView extends HorizontalScrollView
{

private ScrollViewListener scrollViewListener = null;

public ObservableHorizontalScrollView(Context context)
{
super(context);
}

public ObservableHorizontalScrollView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}

public ObservableHorizontalScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}

public void setScrollViewListener(ScrollViewListener scrollViewListener)
{
this.scrollViewListener = scrollViewListener;
}

@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy)
{
super.onScrollChanged(x, y, oldx, oldy);
if (scrollViewListener != null)
{
scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
}
}

}

3.) Interface ScrollViewListener.java

package com.ab1209.etc;

public interface ScrollViewListener
{
void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy);
void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldx, int oldy);
}

And finally the class which implements interface ScrollViewListener and perform simultaneous scrolling.

4.) ScrollTest.java

package com.overflow.ab1209;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import com.overflow.ab1209.etc.ObservableHorizontalScrollView;
import com.overflow.ab1209.etc.ObservableScrollView;
import com.overflow.ab1209.etc.ScrollViewListener;

public class ScrollTest extends Activity implements ScrollViewListener
{
ObservableScrollView scroll_vertical_from_both;
ObservableScrollView scroll_vertical_only;
ObservableHorizontalScrollView scroll_horizontal_from_both;
ObservableHorizontalScrollView scroll_horizontal_only;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.scrolltest);

scroll_vertical_from_both = (ObservableScrollView) findViewById(R.id.scroll_vertical_from_both);
scroll_vertical_only = (ObservableScrollView) findViewById(R.id.scroll_vertical_only);
scroll_horizontal_from_both = (ObservableHorizontalScrollView) findViewById(R.id.scroll_horizontal_from_both);
scroll_horizontal_only = (ObservableHorizontalScrollView) findViewById(R.id.scroll_horizontal_only);

scroll_vertical_from_both.setScrollViewListener(this);
scroll_vertical_only.setScrollViewListener(this);
scroll_horizontal_from_both.setScrollViewListener(this);
scroll_horizontal_only.setScrollViewListener(this);

}

@Override
public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy)
{
// TODO Auto-generated method stub
Log.i(“”,”VERTICAL”);
scroll_vertical_from_both.scrollTo(x, y);
scroll_vertical_only.scrollTo(x, y);
}

@Override
public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldx, int oldy)
{
// TODO Auto-generated method stub
Log.i(“”,”HORIZONTAL”);
scroll_horizontal_from_both.scrollTo(x, y);
scroll_horizontal_only.scrollTo(x, y);

}
}

I hope you liked it & surely will try it and of course make it more innovative.

Thanks

How to use dynamic TableLayout instead of using ListView in Android.

Using ListView for showing data in vertical rows format is always good option but things become difficult when you want to use any widgets in rows of ListView.Although it can be done by using CustomAdapter but when you want to perform action on those widgets (like checking CheckBox or etc.) things become terrifying.For implementig this you need to maintain state of each widget and that part is the difficult one.
For simplicity there is one more way by creating dynamic TableLayout.Although it is complex to implement but once you become familier with it ,it becomes simple.
Here in this example I am creating a dynamic TableLayout whose each row contains a TextView and a Button.Button’s behaviour is made like CheckBox.So on clicking button you can make it check or uncheck.
The advantage of this over using dynamic ListView is you don’t need to worry about saving state of each widget.You can make it easy as any other widget which is static rather than created dynamically.

The XML code is simple.

And in the Java Code .
I have used three special variable

1.) final int CHECK_BUTTON_ID; :– This variable is used for creating ids of dynamically created button (or you can say CheckBox);
2.) int ids_check[]; :– This integer array is array of ids of each Button which is dynamically created in TableRow.
3.) boolean bool_check[]; :– This boolean array is used for keeping knowledge of each Button which is checked or unchecked.

and a very important method createTableRows() :– This method creates the TableRows and all these rows are added to TableLayout.
In this method I have used TableRow,TextView & Button variables whose properties are set by there respective methods.You can customize these by way you want.

*The most important thing in using this way of creating dynamic TableLayout import this android.widget.TableRow.LayoutParams
instead of android.view.ViewGroup.LayoutParams

This is a simple example of dynamic TableLayout with only two widgets you can use as many as you want. It seems to be quit complex but once you done with it you can use with very ease.

package com.ab1209.table.dynamic;

import java.util.ArrayList;
import android.R.bool;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class DynamicTable extends Activity
{
TableLayout table;

ArrayList list_name;

int color_blue = -16776961;
int color_gray = -7829368;
int color_black = -16777216;
int color_white = -1;

final int CHECK_BUTTON_ID = 982301;
int ids_check[];
boolean bool_check[];

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout) findViewById(R.id.tableLayout1);

list_name = new ArrayList();

list_name.add(“Close”);
list_name.add(“Cristiano”);
list_name.add(“David”);
list_name.add(“Fernando”);
list_name.add(“Messi”);
list_name.add(“Kaka’”);
list_name.add(“Wayne”);

bool_check = new boolean[list_name.size()];
ids_check = new int[list_name.size()];
createTableRows();

}

public void createTableRows()
{
for (int i = 0; i < list_name.size(); i++)
{
TableRow table_row = new TableRow(this);
TextView tv_name = new TextView(this);
Button btn_check = new Button(this);
ImageView img_line = new ImageView(this);

table_row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
table_row.setBackgroundColor(color_white);
table_row.setGravity(Gravity.CENTER_HORIZONTAL);

tv_name.setText(list_name.get(i));
tv_name.setTextColor(color_blue);
tv_name.setTextSize(16);
tv_name.setTypeface(Typeface.DEFAULT_BOLD);
tv_name.setWidth(150);

btn_check.setLayoutParams(new LayoutParams(30, 30));
btn_check.setBackgroundResource(R.drawable.small_checkbox_unchecked);

img_line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 2));
img_line.setBackgroundResource(R.drawable.separater_line);

table_row.addView(tv_name);
table_row.addView(btn_check);

table.addView(table_row);
table.addView(img_line);

int id = i + CHECK_BUTTON_ID;
btn_check.setId(id);
ids_check[i] = id;

btn_check.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
for (int j = 0; j < ids_check.length; j++)
{
Button btn_check_1 = (Button) findViewById(ids_check[j]);
if(v.getId() == ids_check[j])
if(bool_check[j])
{
btn_check_1.setBackgroundResource(R.drawable.small_checkbox_unchecked);
bool_check[j] = false;
}
else
{
btn_check_1.setBackgroundResource(R.drawable.small_checkbox_checked);
bool_check[j] = true;
}
}
}
});

}
}
}

Hello world!

Welcome to WordPress.com. After you read this, you should delete and write your own post, with a new title above. Or hit Add New on the left (of the admin dashboard) to start a fresh post.

Here are some suggestions for your first post.

  1. You can find new ideas for what to blog about by reading the Daily Post.
  2. Add PressThis to your browser. It creates a new blog post for you about any interesting  page you read on the web.
  3. Make some changes to this page, and then hit preview on the right. You can always preview any post or edit it before you share it to the world.