Archive

Archive for February, 2013

Multilanguage in android app

First we must create these files: main.xml, MainActivity.java, values-en/string.xml, values-vi/string.xml

Content of these files was created below:

main.xml

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

    <TextView
        android:editable="true"
        android:id="@+id/txt_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/test"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/btn_change1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="VietNam" />

    <Button
        android:id="@+id/btn_change2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="English" />

</LinearLayout>

MainActivity.java

import java.util.Locale;
import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
	Resources res;
	Button btn1,btn2;
	TextView txt;
	String language;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ChangeLang("en");
    }

    public void ChangeLang(String lang)
    {
        Locale locale = new Locale(lang);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
        setContentView(R.layout.main); 
        btn1 = (Button) findViewById(R.id.btn_change1);
        btn2 = (Button) findViewById(R.id.btn_change2);       
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
    } 
	@Override
	public void onClick(View v) 
	{
		if(v == btn1)
		{
			ChangeLang("vi");
			Toast.makeText(getBaseContext(), "1", Toast.LENGTH_SHORT).show();
		}
		if(v == btn2)
		{	
			ChangeLang("en");
			Toast.makeText(getBaseContext(), "2", Toast.LENGTH_SHORT).show();
		}
	}
}

values-en/string.xml

<?xml version=”1.0″ encoding=”utf-8″?>

<resources> <string name=”app_name”>My First Demo</string>

<string name=”test”>This is English</string> </resources>

values-vi/string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="app_name">My First Demo</string>
	<string name="test">Đây là Tiếng Việt</string>
</resources>

You can download full demo at this link https://dl.dropbox.com/u/82707883/multiResource.rar

Source: http://vietandroid.com/threads/multilanguage-da-ngon-ngu.9523/

Categories: Android

My countryside

This  is my countryside.

Categories: Picture

Check network connection

This is a small code to check network state on android phone.

It need for you to check network connection when your application need to connect to the internet

public boolean CheckNetworkConnection(Context context) {
ConnectivityManager conn = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conn.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
|| conn.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING)
return true;
else if (conn.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
|| conn.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED)
return false;
return false;
}

You need to set some permissions in Android Manifest file

– android.permission.INTERNET
– android.permission.ACCESS_NETWORK_STATE

Happy Coding!!!

Categories: Android

Custom Toast

KEY CLASSES

  1. Toast

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. For example, navigating away from an email before you send it triggers a “Draft saved” toast to let you know that you can continue editing later. Toasts automatically disappear after a timeout.

If user response to a status message is required, consider instead using a Notification.

The Basics


First, instantiate a Toast object with one of the makeText() methods. This method takes three parameters: the application Context, the text message, and the duration for the toast. It returns a properly initialized Toast object. You can display the toast notification with show(), as shown in the following example:

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

This example demonstrates everything you need for most toast notifications. You should rarely need anything else. You may, however, want to position the toast differently or even use your own layout instead of a simple text message. The following sections describe how you can do these things.

You can also chain your methods and avoid holding on to the Toast object, like this:

Toast.makeText(context, text, duration).show();

Positioning your Toast


A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

If you want to nudge the position to the right, increase the value of the second parameter. To nudge it down, increase the value of the last parameter.

Creating a Custom Toast View


If a simple text message isn’t enough, you can create a customized layout for your toast notification. To create a custom layout, define a View layout, in XML or in your application code, and pass the root View object to thesetView(View) method.

For example, you can create the layout for the toast visible in the screenshot to the right with the following XML (saved as toast_layout.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toast_layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="8dp"
              android:background="#DAAA"
              >
    <ImageView android:src="@drawable/droid"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginRight="8dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="#FFF"
              />
</LinearLayout>

Notice that the ID of the LinearLayout element is “toast_layout”. You must use this ID to inflate the layout from the XML, as shown here:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
                               (ViewGroup) findViewById(R.id.toast_layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

First, retrieve the LayoutInflater with getLayoutInflater() (or getSystemService()), and then inflate the layout from XML using inflate(int, ViewGroup). The first parameter is the layout resource ID and the second is the root View. You can use this inflated layout to find more View objects in the layout, so now capture and define the content for the ImageView and TextView elements. Finally, create a new Toast withToast(Context) and set some properties of the toast, such as the gravity and duration. Then callsetView(View) and pass it the inflated layout. You can now display the toast with your custom layout by calling show().

Note: Do not use the public constructor for a Toast unless you are going to define the layout withsetView(View). If you do not have a custom layout to use, you must use makeText(Context, int, int)to create the Toast.

 

Source: http://developer.android.com/guide/topics/ui/notifiers/toasts.html

Categories: Android

Wallpaper Example in Android Programming

Posted by  on June 25, 2012, filed in: Android DevelopmentAndroid Programming Tutorials

This example explains how to set wallpaper programmatically for home screen in android.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it WallpaperExample.

2.) Write following into main.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageview" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <Button
            android:id="@+id/randomize"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Randomize"
            android:layout_gravity="bottom" />
        <Button
            android:id="@+id/setwallpaper"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Set as Wallpaper"
            android:layout_gravity="bottom" />
    </LinearLayout>
</FrameLayout>

3.) Set following permission to you manifest file:

<uses-permission android:name="android.permission.SET_WALLPAPER" />

4.) Run for output.

Steps:

1.) Create a project named WallpaperExample and set the information as stated in the image.

Build Target: Android 4.0
Application Name: WallpaperExample
Package Name: com. example. WallpaperExample
Activity Name: WallpaperExample
Min SDK Version: 14

2.) Open WallpaperExample.java file and write following code there:

package com.example.WallpaperExample;
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class WallpaperExample extends Activity {
    final static private int[] mColors =
    {Color.BLUE, Color.GREEN, Color.RED, Color.LTGRAY, Color.MAGENTA, Color.CYAN,
        Color.YELLOW, Color.WHITE};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Be sure to call the super class.
        super.onCreate(savedInstanceState);
        // See res/layout/wallpaper_2.xml for this
        // view layout definition, which is being set here as
        // the content of our screen.
        setContentView(R.layout.main);
        final WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
        final Drawable wallpaperDrawable = wallpaperManager.getDrawable();
        final ImageView imageView = (ImageView) findViewById(R.id.imageview);
        imageView.setDrawingCacheEnabled(true);
        imageView.setImageDrawable(wallpaperDrawable);
        Button randomize = (Button) findViewById(R.id.randomize);
        randomize.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                int mColor = (int) Math.floor(Math.random() * mColors.length);
                wallpaperDrawable.setColorFilter(mColors[mColor], PorterDuff.Mode.MULTIPLY);
                imageView.setImageDrawable(wallpaperDrawable);
                imageView.invalidate();
            }
        });
        Button setWallpaper = (Button) findViewById(R.id.setwallpaper);
        setWallpaper.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                try {
                    wallpaperManager.setBitmap(imageView.getDrawingCache());
                    finish();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

3.) Compile and build the project.

Output

 

Source: http://www.edumobile.org/android/android-development/wallpaper-example-in-android-programming/

Categories: Android