Saturday, May 19, 2012

Android: Expand Liner Layout Beyond its Width

In android, the layout weight parameter in the liner layout is very useful to layout views with relative ratios. Say you want to arrange two frames left and right, and right frame take quoter and right take the balance.


We can simply create this using following layout xml. Only thing is to noted down is, the width should be set to 0dip and weight to be set to 0.25 or 0.75 according to the requirement. That all.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:weightSum="1" >

    <FrameLayout
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="0.75"
        android:background="#FF0000" >
    </FrameLayout>

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.25"
        android:background="#00FF00" >

        <ToggleButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />
    </FrameLayout>

</LinearLayout>


But in our case, we wanted to add another frame next to the right frame its width also 0.75 of the screen and in some user action, by moving the screen, the left frame should be hidden and 3rd frame should be shown.



So we created custom liner layout by extending the liner layout, where we override the on measure method to adjust its size by 0.75 of its size.


public class ExpandedLinearLayout extends LinearLayout {
@SuppressWarnings("unused")
private static final String TAG = "demo.beyond.layout.ExpandedLinearLayout";
public ExpandedLinearLayout(Context context) {
super(context);
}
public ExpandedLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExpandedLinearLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension((int) (1.75f*getMeasuredWidth()), getMeasuredHeight());
}
}



And add another new frame to above layout with weight 0.75.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
.................    
    <FrameLayout
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="0.75"
        android:background="#0000FF" >
    </FrameLayout>

</LinearLayout>


Then we add the animation for the on click.


public class DemoExpandLayoutActivity extends Activity implements OnClickListener {
        private LinearLayout mLinearLayout;
private FrameLayout mFrameLayout1;
private ToggleButton mToggleButton;
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mLinearLayout = (LinearLayout)findViewById(R.id.frame);
        mFrameLayout1 = (FrameLayout)findViewById(R.id.frameLayout1);
        mToggleButton = (ToggleButton)findViewById(R.id.toggleButton1);
        mToggleButton.setOnClickListener(this);
    }

@Override
public void onClick(View arg0) {
float factor = 1.0f*mFrameLayout1.getWidth()/mLinearLayout.getWidth();
if(mToggleButton.isChecked()){
mLinearLayout.setTranslationX(-mFrameLayout1.getWidth());
TranslateAnimation translateAnimation = new TranslateAnimation(
TranslateAnimation.RELATIVE_TO_PARENT,
factor,
TranslateAnimation.RELATIVE_TO_PARENT,
0.0f,
TranslateAnimation.RELATIVE_TO_PARENT,
0.0f,
TranslateAnimation.RELATIVE_TO_PARENT,
0.0f);
translateAnimation.setDuration(1000);
LayoutAnimationController layoutAnimationController = new LayoutAnimationController(translateAnimation,0.1f);
mLinearLayout.setLayoutAnimation(layoutAnimationController);
}else{
mLinearLayout.setTranslationX(0);
TranslateAnimation translateAnimation = new TranslateAnimation(
TranslateAnimation.RELATIVE_TO_PARENT,
-factor,
TranslateAnimation.RELATIVE_TO_PARENT,
0.0f,
TranslateAnimation.RELATIVE_TO_PARENT,
0.0f,
TranslateAnimation.RELATIVE_TO_PARENT,
0.0f);
translateAnimation.setDuration(1000);
LayoutAnimationController layoutAnimationController = new LayoutAnimationController(translateAnimation,-0.1f);
mLinearLayout.setLayoutAnimation(layoutAnimationController);
}
}
}


But that didn't quit worked out, because liner layout ignores views If those out side the weight sum.

But if we add views as match patent, with layout weights, liner layout behaves differently. It draws all the views beyond its boundary.
In this case the actual width of each view was not proportional to layout weight what we set in layout XML.
So to find out the relation, I just try for different values and plot the following graph and got the below equation.



I couldn't find any direct evidence in android code base or may have to check some more android source code. But this is good enough to calculate the proper values for us.

Then I changed the layout XML with those values.


<?xml version="1.0" encoding="utf-8"?>
<demo.beyond.layout.ExpandedLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/frame"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:weightSum="1" >

    <FrameLayout
        android:id="@+id/frameLayout1"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.125"
        android:background="#FF0000" >
    </FrameLayout>

    <FrameLayout
        android:id="@+id/frameLayout2"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.375"
        android:background="#00FF00" >

        <ToggleButton
            android:id="@+id/toggleButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />
    </FrameLayout>

    <FrameLayout
        android:id="@+id/frameLayout3"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.125"
        android:background="#0000FF" >
    </FrameLayout>

</demo.beyond.layout.ExpandedLinearLayout>


Further more I modified the expanded liner layout with this formula, so that it can use in all cases.


@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int numberOfChild = getChildCount();
float totalWidth = 0;
for(int i = 0;i < numberOfChild;i++){
totalWidth+=getMeasuredWidth()
*(1 - 2*((LinearLayout.LayoutParams)getChildAt(i).getLayoutParams()).weight);
}
setMeasuredDimension((int) totalWidth, getMeasuredHeight());
}


Here I have uploaded the source code, try it your self and let me know your feedback or let me know if you have any other option.





Tuesday, May 15, 2012

Android: How to Check if Media Scanner is Running?

In our application, some of the action need to be blocked while android media scanner running (For example loading existing media and listing down).

In this case, we couldn't find a direct API to check if Media Scanner is running. We could find following two options:
Option 01:
Android will broadcast Intent.ACTION_MEDIA_SCANNER_STARTEDIntent.ACTION_MEDIA_SCANNER_FINISHED in starting and finishing of scanning respectively. So we create following  BroadcastReceiver:

public class MediaScannerBroadcastReceiver extends BroadcastReceiver {
public static boolean mMedaiScanning = false;
        @Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_MEDIA_SCANNER_STARTED)){
mMedaiScanning = true;
}
if(intent.getAction().equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)){
mMedaiScanning = false;
}
}
}


And register this in manifest file:

<receiver android:name=" MediaScannerBroadcastReceiver">
     < intent-filter>

           < action android:name="android.intent.action.MEDIA_SCANNER_FINISHED" >  < /action>
          < action android:name="android.intent.action.MEDIA_SCANNER_STARTED" >  < /action>
           < data android:scheme="file" >  < /data>
      < /intent-filter>
</receiver>


Then in cases we we wanted to check the condition we sued as following:
if( MediaScannerBroadcastReceiver.mMedaiScanning){
     .....
}

But, most of the devices will run Media Scanner in boot up, in adding SDCard or mount/unmount devices to PC. In those cases our application is invoked and loaded into memory.

Option 02:
found that the media scanner service insert and delete a record into media store when starting and finishing the scanning. So we try to check the record in the media store as follows:

private boolean isMediaScannerRunning() {
Cursor query = getContentResolver().query(MediaStore.getMediaScannerUri(),
                                                   new String[]{MediaStore.MEDIA_SCANNER_VOLUME}, nullnullnull);
        if(query!=null){
         if(query.moveToFirst()){
         int columnIndex = query.getColumnIndex(MediaStore.MEDIA_SCANNER_VOLUME);
         String volumeName = query.getString(columnIndex);
         if(volumeName!=null){
         return true;
         }
         }
         query.close();
        }
        return false;
}

This option will not load the application while media scanner running. But need to consider its costly operation in query.

Lets check both options for its pros and cons.

Saturday, October 1, 2011

Part 7: Thoughts of “How we do?” - Reading from Near vs Far


Say you are traveling in a bus and trying to read a board on both sides of the road. First board is on the same side where you are traveling and the second board on the other side of the road. Both has same text. And the board on the opposite side has enough font size to read it from the bus which you are traveling. Normally we can only star reading once we come inside the visual angle of the board.

Assume you are reading both boards in two different situation from start to end while bus moving in same speed. You will understand that, you can read more from the board which is in the opposite side. So when we are traveling, without reducing our speed, we can't read more from near, rather from far we can. But the distance should be enough to identify the letters, that all.

Now, let see how we can apply this into a real life situations.

Team leaders, if your team members are currently working in a project with a constant speed. And you are hearing some new project opportunity. It is not good to wait until your project got confirm and then bring it to the members to their close attention. Because members have to slowdown their current project in order to prepare the new project. Instead of that, if you let them prepare the new project early as possible in a relax mode,  this will not much affect the current project speed.

Here one of the different between close attention and relax mode would be, in close attention team leader will expect and check for updates very frequently, rather in relax mode leader could wait until the team member bring updates to leaders' table or expect and check update occasionally.

One concern may be: change in the project detail will make the preparation waste, but that is not fully true. Because if we have already prepared and then you summaries the different from early draft we don't need much effect to override the new changes. If the project details totally change, then of cause all the initial preparation is waste. Mostly that not the case.

But for the success of relax mode approach, team member should have enough skill level. They should be proactive to prepare project in early stage, self motivated to prepare project and provide updates. They should be able manage and balance work load in preparation new project with the current project.

Feather more, letting the team member to prepare the project early will lead to understand any unclear or impossible areas in the project so that the project could be modify accordingly. This will help in project executions very much.

So, I feel it is better to do go for a early preparation of new project. Both team leaders and members should understand the pros and cons in this approach and should act accordingly. This will bring a best team and best product in the end.

Let me find out another real example as above and meet you another post. Bye 

Android : Drawing View with shapes plotted in r theta (r,θ) relation

r = 0.875*width/2+0.125cos(12θ)
r - width/2*cos(4θ)
r - width/2
Say you want to create views which contains shares as shown above. In those each circle drawn in (r,θ) relation. I implemented following onDraw method with possible two options.
Option 1. Rotating canvas and drawing circles - this is direct use of (r , θ)
Option 2. Converting points into x,y plan coordinate and drawing the circle.


@Override
protected void onDraw(Canvas canvas) {
float width = getWidth()/2;
float height = getHeight()/2;
Paint paint = new Paint();
paint.setColor(Color.RED);
        //Option 1
long time = System.currentTimeMillis();
canvas.save();
canvas.translate(width, height);
for(int i = 0 ; i < 13;i++){
canvas.drawCircle(width, 0, width*0.2f, paint);
canvas.rotate(-15);
}
canvas.restore();
Log.i(TAG, "::onDraw:" + "time 1 = " + (System.currentTimeMillis()-time));
        //Option 2
long time1 = System.currentTimeMillis();
canvas.save();
canvas.translate(width, height);
float angle = 0;
for(int i = 0 ; i < 13;i++){
float radian = (float) (Math.PI*angle/180.0f);
canvas.drawCircle((float) (width*Math.cos(radian)),
(float) (width*Math.sin(radian)), width*0.2f, paint);
angle+=15;
}
canvas.restore();
Log.i(TAG, "::onDraw:" + "time 2 = " + (System.currentTimeMillis()-time1));
}

Since above coding draw only 13 circles, I couldn't find a clear different in execution time for both options. So I change the code to draw 180 circle as follows:


@Override
protected void onDraw(Canvas canvas) {
float width = getWidth()/2;
float height = getHeight()/2;
Paint paint = new Paint();
paint.setColor(Color.RED);
long time1 = System.currentTimeMillis();
canvas.save();
canvas.translate(width, height);
for(int i = 0 ; i < 180;i++){
float radius = width;
canvas.drawCircle(radius, 0, 2.0f, paint);
canvas.rotate(-1);
}
canvas.restore();
time1 = System.currentTimeMillis()-time1;
long time2 = System.currentTimeMillis();
canvas.save();
canvas.translate(width, height);
for(int i = 0 ; i < 180;i++){
float radian = (float) (Math.PI*i/180.0f);
float radius = width;
canvas.drawCircle((float) (radius*Math.cos(radian)),
(float) (radius*Math.sin(radian)), 2.0f, paint);
}
canvas.restore();
time2 = System.currentTimeMillis()-time2;
Log.i(TAG, "::onDraw:" + "time1,time2, (time1-time2) = "
+ time1 + ","+time2+","+(time1-time2));
}

Now i could see clear different and Option 2 is faster than Option 1.



INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 62,35,27
INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 66,36,30
INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 66,37,29
INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 63,35,28
INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 68,34,34
INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 63,35,28
INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 61,35,26
INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 59,35,24
INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 68,40,28
INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 75,32,43
INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 65,32,33
INFO/demo.theta.DemoRTheta(5302): ::onDraw:time1,time2, (time1-time2) = 52,36,16


Here you have expresions for other above graphs. 

float radian = (float) (Math.PI*i/180.0f);

float radius = width;
float radius = (float) (width*Math.cos(4*radian));
float radius = (float) (0.875f*width+0.125f*width*Math.cos(12*radian));



But Option 2 needs some extra calculation to translate  (r , θ) into (x, y), in above examples we needed to determine only center of the circle.
Let see some of the view as follows.
canvas.save();
canvas.translate(width, height);
for(int i = 0 ; i < 72;i++){
canvas.drawLine(width*0.8F, 0, width*1.0f, 0, paint);
canvas.rotate(5);
}
canvas.restore();

Now we have to find start x,y and end x,y that need extra calculation and extra analysis effect to come up with that expresion.
Next one is more interesting need to use Path.

canvas.save();
canvas.translate(width, height);
for(int i = 0 ; i < 18;i++){
Path path = new Path();
path.moveTo(width*0.8F, 0);
path.lineTo(width, width*0.1F);
path.lineTo(width, -width*0.1F);
path.lineTo(width*0.8F, 0);
canvas.drawPath(path, paint);
canvas.rotate(20);
}
canvas.restore();

Now you can find translation expression and can find out which one is faster in each cases.
Enjoy!

Tuesday, September 27, 2011

Grid, Adaptor, left to right into top to bottom

Say we have list of object as follows,
list =
.size() = 14
and need to show it in grid control that scroll vertically as follows,
// assume we want three columns.
int columns = 3;
// first calculate number of rows.
int rows = (columns-1+list.size())/columns;

Or into grid control that scroll horizontally as follows,
//assume we want three rows.
int rows = 3;
// first calculate number of rows.
int columns = (rows-1+list.size())/rows;

Mostly we use adaptor to fetch the item to show in each cell.
In this case adaptor can choose the index equal to position, 

int index = position;
return list.get(index); 

But say some cases we may have to change to order in display. for example. top to bottom as shown below:
But if the control fetch base on position from left to right as show below:
then, we need to add proper calculation inside the adaptor:

int index =position/columns+position%columns*rows;
return list.get(index); 

Thursday, September 15, 2011

Android: Aligning Custom Views at Base Line

Have you ever try to align a non-symmetric custom view at a custom base line as follows?


I tried it using base line attribute of Relative Layout.
First adjust the size of view:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//Height should be always width * 7 / 12
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()*7/12);
}


Then Override the getBaseLine method:
@Override
public int getBaseline() {
//base line is from bottom to width/12 (radius of the blue circle)
return getMeasuredHeight()-getMeasuredWidth()/12;
}


Following onDraw method would explain the reason for the above calculation:

@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setAntiAlias(true);
//Draw the half circle
paint.setColor(Color.GRAY);
float width = getWidth();
float height = getHeight();
canvas.save();
canvas.translate(width/2, height-width/12);
canvas.drawArc(new RectF(-width/3, -width/3, +width/3, width/3), 0, -180, true, paint);
//Draw small circles
paint.setColor(Color.DKGRAY);
RectF rectF = new RectF(-width/2+width/24, -width/12+width/24, -width/3-width/24,                +width/12-width/24);
canvas.drawOval(rectF, paint);
for(int i = 0 ; i < 15 ;i++){
canvas.rotate(12f);
canvas.drawOval(rectF, paint);
}
//Draw blue circle
paint.setColor(Color.BLUE);
canvas.rotate(-180+30);
canvas.drawOval(new RectF(-width/2, -width/12, -width/3, +width/12), paint);
//Draw red arrow
paint.setColor(Color.RED);
Path path = new Path();
path.moveTo(-width*5/12, 0);
path.lineTo(10, -width/12);
path.lineTo(0, 0);
path.lineTo(10, +width/12);
path.close();
canvas.drawPath(path, paint);
canvas.restore();
}


Finally, create a layout xml as following:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<demo.ui.testing.DemoUITesting
android:layout_height="fill_parent" android:layout_width="fill_parent"
android:layout_alignBaseline="@+id/radioButton1"
android:layout_toRightOf="@+id/radioButton1">
<RadioButton android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/radioButton1"
android:layout_centerVertical="true">
</RelativeLayout>

Enjoy!.

Wednesday, September 14, 2011

Android: convert Immutable Bitmap into Mutable

Android provide Bitmap class to manipulate images. We can load, draw, edit or save. But incase of editing bitmap should be mutable.

For example:
Canvas canvas = new Canvas(mBitmap);
Will throw IllegalArgumentException: image is immuable ...

An image file can be loaded in to bitmap using BitmapFactory as follows:

mBitmap = BitmapFactory.decodeFile(path);

But this will be an immutable bitmap. This will not be able to edited.

Anyway can load image using BitmapFactory.decodeFile(path,options);
Here BitmapFactory.Options options = new BitmapFactory.Options();

But from API Level 11 only options.inMutable available to load the file into a mutable bitmap.

So, if we are building application with API level less than 11, then we have to find some other alternatives.

One alternative is creating another bitmap by copying the source bitmap.
mBitmap = mBitmap.copy(ARGB_8888 ,true);

But the will throw OutOfMemoryException if the source file is big. Actually incase if we want to edit an original file, then we will face this issue. We should be able to load at-least image into memory, but most we can not allocate another copy into memory.

So, we have to save the decoded bytes into some where and clear existing bitmap, then create a new mutable bitmap and load back the  saved bytes into bitmap again. Even to copy bytes we cannot create another ByteBuffer inside the memory. In that case need to use MappedByteBuffer that will allocate bytes inside a disk file.

Following code would explain clearly:

//this is the file going to use temporally to save the bytes. 

File file = new File("/mnt/sdcard/sample/temp.txt");
file.getParentFile().mkdirs();

//Open an RandomAccessFile
/*Make sure you have added uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
into AndroidManifest.xml file*/
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); 

// get the width and height of the source bitmap.
int width = bitmap.getWidth();
int height = bitmap.getHeight();

//Copy the byte to the file
//Assume source bitmap loaded using options.inPreferredConfig = Config.ARGB_8888;
FileChannel channel = randomAccessFile.getChannel();
MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, width*height*4);
bitmap.copyPixelsToBuffer(map);
//recycle the source bitmap, this will be no longer used.
bitmap.recycle();
//Create a new bitmap to load the bitmap again.
bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
map.position(0);
//load it back from temporary 
bitmap.copyPixelsFromBuffer(map);
//close the temporary file and channel , then delete that also
channel.close();
randomAccessFile.close();

Hope this wil help you.

I have uploaded the sample source code here:
http://dl.dropbox.com/u/7717254/DemoPaint.zip
In which application, user can load a image and draw and save back. In case of saving back to original image size.