Wednesday, 29 May 2019

How to write simple txt file in External Storage






Simple Write data/data/package name/files/sample.txt content into  external storage


public void writeOnInternalStorageDir(Context mContext, String sFileName, String sBody) {
    File file = new File(mContext.getFilesDir(), "FolderName");
    if (!file.exists()) {
        file.mkdir();
    }

    try {
        File gpxfile = new File(file, sFileName);
        if (!gpxfile.exists()) {
            gpxfile.createNewFile();
        }
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example :  
writeOnInternalStorageDir(MainActivity.this,"sample.txt","Welcome chandkony.blogspot.com");

Wednesday, 10 October 2018

Add maven google link in android studio project build.gradle

]

Example :

allprojects {
    repositories {
        jcenter()

-------------------------------------------
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
-------------------------------------------

    }
}

Friday, 23 March 2018

Backup Sqlite Database from mobile app



                                               Backup Sqlite Database from mobile app


 public void backDB()
    {

        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "/data/data/" + getPackageName() + "/databases/databasename.db";
                String backupDBPath = "databasename.db";
                File currentDB = new File(currentDBPath);
                File backupDB = new File(sd, backupDBPath);

                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        } catch (Exception e) {

        }
    }


AndroidManifest.xml

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

Thursday, 8 March 2018

How to Get the Time spent for an application in Android Programmatically



 
                              Apps with usage access settings



Activity Classes :-

package com.example.android.appusagestatistics;

import android.app.Activity;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import android.text.format.DateUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

/** * Activity to display package usage statistics. */public class UsageStatsActivity extends Activity implements OnItemSelectedListener {
    private static final String TAG = "UsageStatsActivity";
    private static final boolean localLOGV = false;
    private UsageStatsManager mUsageStatsManager;
    private LayoutInflater mInflater;
    private UsageStatsAdapter mAdapter;
    private PackageManager mPm;

    public static class AppNameComparator implements Comparator<UsageStats> {
        private Map<String, String> mAppLabelList;

        AppNameComparator(Map<String, String> appList) {
            mAppLabelList = appList;
        }

        @Override        public final int compare(UsageStats a, UsageStats b) {
            String alabel = mAppLabelList.get(a.getPackageName());
            String blabel = mAppLabelList.get(b.getPackageName());
            return alabel.compareTo(blabel);
        }
    }

    public static class LastTimeUsedComparator implements Comparator<UsageStats> {
        @Override        public final int compare(UsageStats a, UsageStats b) {
            // return by descending order            return (int)(b.getLastTimeUsed() - a.getLastTimeUsed());
        }
    }

    public static class UsageTimeComparator implements Comparator<UsageStats> {
        @Override        public final int compare(UsageStats a, UsageStats b) {
            return (int)(b.getTotalTimeInForeground() - a.getTotalTimeInForeground());
        }
    }

    // View Holder used when displaying views    static class AppViewHolder {
        TextView pkgName;
        TextView lastTimeUsed;
        TextView usageTime;
    }

    class UsageStatsAdapter extends BaseAdapter {
        // Constants defining order for display order        private static final int _DISPLAY_ORDER_USAGE_TIME = 0;
        private static final int _DISPLAY_ORDER_LAST_TIME_USED = 1;
        private static final int _DISPLAY_ORDER_APP_NAME = 2;

        private int mDisplayOrder = _DISPLAY_ORDER_USAGE_TIME;
        private LastTimeUsedComparator mLastTimeUsedComparator = new LastTimeUsedComparator();
        private UsageTimeComparator mUsageTimeComparator = new UsageTimeComparator();
        private AppNameComparator mAppLabelComparator;
        private final ArrayMap<String, String> mAppLabelMap = new ArrayMap<>();
        private final ArrayList<UsageStats> mPackageStats = new ArrayList<>();

        UsageStatsAdapter() {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, -5);

            final List<UsageStats> stats =
                    mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,
                            cal.getTimeInMillis(), System.currentTimeMillis());
            if (stats == null) {
                return;
            }

            ArrayMap<String, UsageStats> map = new ArrayMap<>();
            final int statCount = stats.size();
            for (int i = 0; i < statCount; i++) {
                final android.app.usage.UsageStats pkgStats = stats.get(i);

                // load application labels for each application                try {
                    ApplicationInfo appInfo = mPm.getApplicationInfo(pkgStats.getPackageName(), 0);
                    String label = appInfo.loadLabel(mPm).toString();
                    mAppLabelMap.put(pkgStats.getPackageName(), label);

                    UsageStats existingStats =
                            map.get(pkgStats.getPackageName());
                    if (existingStats == null) {
                        map.put(pkgStats.getPackageName(), pkgStats);
                    } else {
                        existingStats.add(pkgStats);
                    }

                } catch (NameNotFoundException e) {
                    // This package may be gone.                }
            }
            mPackageStats.addAll(map.values());

            // Sort list            mAppLabelComparator = new AppNameComparator(mAppLabelMap);
            sortList();
        }

        @Override        public int getCount() {
            return mPackageStats.size();
        }

        @Override        public Object getItem(int position) {
            return mPackageStats.get(position);
        }

        @Override        public long getItemId(int position) {
            return position;
        }

        @Override        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls            // to findViewById() on each row.            AppViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need            // to reinflate it. We only inflate a new View when the convertView supplied            // by ListView is null.            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.usage_stats_item, null);

                // Creates a ViewHolder and store references to the two children views                // we want to bind data to.                holder = new AppViewHolder();
                holder.pkgName = (TextView) convertView.findViewById(R.id.package_name);
                holder.lastTimeUsed = (TextView) convertView.findViewById(R.id.last_time_used);
                holder.usageTime = (TextView) convertView.findViewById(R.id.usage_time);
                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView                // and the ImageView.                holder = (AppViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder            UsageStats pkgStats = mPackageStats.get(position);
            if (pkgStats != null) {
                String label = mAppLabelMap.get(pkgStats.getPackageName());
                holder.pkgName.setText(label);
                holder.lastTimeUsed.setText(DateUtils.formatSameDayTime(pkgStats.getLastTimeUsed(),
                        System.currentTimeMillis(), DateFormat.MEDIUM, DateFormat.MEDIUM));
                holder.usageTime.setText(
                        DateUtils.formatElapsedTime(pkgStats.getTotalTimeInForeground() / 1000));
            } else {
                Log.w(TAG, "No usage stats info for package:" + position);
            }
            return convertView;
        }

        void sortList(int sortOrder) {
            if (mDisplayOrder == sortOrder) {
                // do nothing                return;
            }
            mDisplayOrder= sortOrder;
            sortList();
        }
        private void sortList() {
            if (mDisplayOrder == _DISPLAY_ORDER_USAGE_TIME) {
                if (localLOGV) Log.i(TAG, "Sorting by usage time");
                Collections.sort(mPackageStats, mUsageTimeComparator);
            } else if (mDisplayOrder == _DISPLAY_ORDER_LAST_TIME_USED) {
                if (localLOGV) Log.i(TAG, "Sorting by last time used");
                Collections.sort(mPackageStats, mLastTimeUsedComparator);
            } else if (mDisplayOrder == _DISPLAY_ORDER_APP_NAME) {
                if (localLOGV) Log.i(TAG, "Sorting by application name");
                Collections.sort(mPackageStats, mAppLabelComparator);
            }
            notifyDataSetChanged();
        }
    }

    /** Called when the activity is first created. */    @Override    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.usage_stats);

        mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
        mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mPm = getPackageManager();

        Spinner typeSpinner = (Spinner) findViewById(R.id.typeSpinner);
        typeSpinner.setOnItemSelectedListener(this);

        ListView listView = (ListView) findViewById(R.id.pkg_list);
        mAdapter = new UsageStatsAdapter();
        listView.setAdapter(mAdapter);
    }

    @Override    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        mAdapter.sortList(position);
    }

    @Override    public void onNothingSelected(AdapterView<?> parent) {
        // do nothing    }
}
 
 
 
Layout :-
 
1. usage_stats.xml
 
 

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

    <TextView 
 android:text="@string/display_order_text" 
 android:textAppearance="?android:attr/textAppearanceLarge" 
 android:layout_width="match_parent"
 android:layout_height="wrap_content" />

    <Spinner
        android:id="@+id/typeSpinner" 
 android:layout_width="match_parent"
        android:layout_height="wrap_content" 
 android:entries="@array/usage_stats_display_order_types" />

    <LinearLayout 
 android:orientation="horizontal" 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" >
        <TextView 
 android:text="@string/app_name_label" 
 android:textAppearance="?android:attr/textAppearanceMedium" 
 android:layout_width="wrap_content" 
 android:paddingEnd="6dip" 
 android:layout_height="wrap_content" />
        <TextView 
 android:text="@string/last_time_used_label" 
 android:paddingEnd="6dip" 
 android:textAppearance="?android:attr/textAppearanceMedium" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" />
        <TextView 
 android:text="@string/usage_time_label" 
 android:textAppearance="?android:attr/textAppearanceMedium" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" />
    </LinearLayout>
    <ListView android:id="@+id/pkg_list" 
 android:layout_width="match_parent"  
 android:layout_height="match_parent" 
 android:drawSelectorOnTop="false" />
</LinearLayout>
 

 
2. usage_stats_item.xml 
 
<?xml version="1.0" encoding="utf-8"?>
 
 <!--/*** Copyright 2008, The Android Open Source Project 
     ****Licensed under the Apache License, Version 2.0 (the "License"); 
    ** you may not use this file except in compliance with the License.**
    You may obtain a copy of the License at 
****     http://www.apache.org/licenses/LICENSE-2.0 
**** Unless required by applicable law or agreed to in writing, software 
** distributed under the License is distributed on an "AS IS" BASIS, 
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
** See the License for the specific language governing permissions and 
** limitations under the License.*/--> 
<LinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content" 
     android:minHeight="?android:attr/listPreferredItemHeight" 
      android:orientation="horizontal">

    <TextView android:id="@+id/package_name"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content" 
       android:maxLines="1" 
       android:paddingEnd="6dip" 
       android:paddingStart="12dip" 
       android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView 
           android:id="@+id/last_time_used"
           android:layout_width="wrap_content" 
           android:layout_height="wrap_content" 
           android:maxLines="1" 
           android:paddingEnd="6dip" 
           android:paddingStart="12dip" 
           android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView 
            android:id="@+id/usage_time" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:maxLines="1" 
            android:paddingEnd="6dip" 
           android:paddingStart="12dip" 
           android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>



Values :-
 
arrays.xml
 
<?xml version="1.0" encoding="utf-8"?><resources>


    <string-array name="usage_stats_display_order_types">
        <item>Usage time</item>
        <item>Last time used</item>
        <item>App name</item>
    </string-array>
</resources>
 
 
string.xml
 
 <string name="open_app_usage_setting">Open Apps with usage access settings</string>
<string name="last_time_used">"Last time used: "</string>
<string name="time_span">"Time span: "</string>
<string name="display_order_text">Sort by:</string>
<string name="app_name_label">App</string>
<string name="last_time_used_label">Last time used</string>
<!-- label for usage time --><string name="usage_time_label">Usage time</string> 



 
 
user permissions :-
 
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>
 
 
OUT PUT
 
 
 
 
 
 

Wednesday, 17 January 2018

Android Unique Device ID



                                                       
Android Unique Device ID



Secure  Android Unique Device ID

       On a device first boot, a randomly value is generated and stored. The Android_ID is a unique 64 bit number that is generated and stored when the device is first booted. The Android_ID is wiped out when the device is Factory reset and new one gets generated. It’s a 64-bit number that should remain constant for the lifetime of a device



String unique_deviceid = Settings.Secure.getString(getApplicationContext()
.getContentResolver(),Settings.Secure.ANDROID_ID);

TextView textView = (TextView)findViewById(R.id.textView_deviceID);
textView.setText(unique_id);



Screeenshot :-


            






Tuesday, 20 June 2017

How to restart an application programmatically in android


 
The following code snippet shows how to restart an android application after the specified delay
programmatically:


public void restart(int delay) {
    PendingIntent intent = PendingIntent.getActivity(this.getBaseContext(), 0, new Intent(getIntent()), PendingIntent.FLAG_ONE_SHOT);
    AlarmManager manager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    manager.set(AlarmManager.RTC, System.currentTimeMillis() + delay, intent);
    System.exit(2);
}

Friday, 19 August 2016

ALL TextView's typefaces, includes action bar and other standard components, but EditText's password font won't be overriden.




Reference URL : https://gist.github.com/artem-zinnatullin/7749076?signup=true



public class MyApp extends Application {
@Override
public void onCreate() {
TypefaceUtil.overrideFont(getApplicationContext(), "SERIF", "fonts/Roboto-Regular.ttf"); // font from assets: "assets/fonts/Roboto-Regular.ttf
}
}






<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyAppTheme" parent="@android:style/Theme.Holo.Light">
<!-- you should set typeface which you want to override with TypefaceUtil -->
<item name="android:typeface">serif</item>
</style>
</resources>




import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.lang.reflect.Field;
public class TypefaceUtil {
/**
* Using reflection to override default typeface
* NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
* @param context to work with assets
* @param defaultFontNameToOverride for example "monospace"
* @param customFontFileNameInAssets file name of the font from assets
*/
public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {
try {
final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);
final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
defaultFontTypefaceField.setAccessible(true);
defaultFontTypefaceField.set(null, customFontTypeface);
} catch (Exception e) {
Log.e("Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
}
}
}

Easiest way to hide keyboard in fragment or Activity


Soluton : 1


    //hide keyboard
    public static void hideKeyboard(Context ctx) {
        InputMethodManager inputManager = (InputMethodManager) ctx
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        // check if no view has focus:
        View v = ((Activity) ctx).getCurrentFocus();
        if (v == null)
            return;

        inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }



Solution : 2


        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
   





Solution : 3 for Table layout (TAB selected based hid the keyboard)

http://stackoverflow.com/questions/10297376/how-do-i-hide-the-soft-keyboard-when-changing-tabs








Friday, 12 August 2016

Take Backup Sqlite Database from device programmatically


package com.example.sample;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.truetech.nec.util.NECSharedPref;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

public class SplashScreen extends BaseActivity {


    // Splash screen timer    private static int SPLASH_TIME_OUT = 3000;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen_activity);




    
          //fucntion for taking sqlite database backup programmatically
          backupDB();

    }


 //fucntion for taking sqlite database backup programmatically
private void backupDB() {

    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "/data/data/" + getPackageName() + "/databases/database.db";
            String backupDBPath = "databasename.db";
            File currentDB = new File(currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {

    }
}

Monday, 2 May 2016

Custom Dialog in Android Using Dialog Interface


Custom Dialog Popup Window using Android with Help of Dialog Interface


Main Activity onCreate()

To write the code inside the onclick event.


   btn_next = (Button)findViewById(R.id.btn_next);
        btn_next.setOnClickListener(new View.OnClickListener() {

            @Override            public void onClick(View v) {
                CustomizeDialog customDiglog= new CustomizeDialog(context);
                customDiglog.setTitle("Hello Welocme");
                customDiglog.setMessage("Hello Welocme");
                customDiglog.show();
            }
        });
    }
 
Custome Dialog Class
 
 
 import android.app.Dialog;
import android.content.Context;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
/** Class Must extends with Dialog */
 /** 
Implement onClickListener to dismiss dialog when OK Button is pressed */
 public class CustomizeDialog extends Dialog implements OnClickListener {
    Button okButton;
    Context mContext;
    TextView mTitle = null;
    TextView mMessage = null;
    View v = null;
    public CustomizeDialog(Context context) {
        super(context);
        mContext = context;
        /** 'Window.FEATURE_NO_TITLE' - Used to hide the mTitle */         
         requestWindowFeature(Window.FEATURE_NO_TITLE);
        /** Design the dialog in main.xml file */ 
         setContentView(R.layout.dialog_msg);
        v = getWindow().getDecorView();
        v.setBackgroundResource(android.R.color.transparent);
        mTitle = (TextView) findViewById(R.id.dialogTitle);
        mMessage = (TextView) findViewById(R.id.dialogMessage);
        okButton = (Button) findViewById(R.id.OkButton);
        okButton.setOnClickListener(this);
    }
    @Override    public void onClick(View v) {
        /** When OK Button is clicked, dismiss the dialog */        if (v == okButton)
            dismiss();
    }
    @Override    public void setTitle(CharSequence title) {
        super.setTitle(title);
        mTitle.setText(title);
    }
    @Override    public void setTitle(int titleId) {
        super.setTitle(titleId);
        mTitle.setText(mContext.getResources().getString(titleId));
    }
    /**     * Set the message text for this dialog's window.     * 
 * @param message     *      - The new message to display in the title.     */ 
 public void setMessage(CharSequence message) {
        mMessage.setText(message);
        mMessage.setMovementMethod(ScrollingMovementMethod.getInstance());
    }
    /**     * Set the message text for this dialog's window. 
The text is retrieved from the resources with the supplied     * identifier. 
 *     * @param messageId     *      - the message's text resource identifier <br>
     * @see <b>Note : if resourceID wrong application may get crash.</b><br>
     *   Exception has not handle.     */    public void setMessage(int messageId) {
        mMessage.setText(mContext.getResources().getString(messageId));
        mMessage.setMovementMethod(ScrollingMovementMethod.getInstance());
    }
}
 
 
Layout xml file
 
 
dialog_msg.xml 

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout  
xmlns:android="http://schemas.android.com/apk/res/android" 
      android:id="@+id/LinearLayout" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:layout_margin="0dip" 
      android:background="@drawable/alert_bg"     
      android:orientation="vertical" 
      android:paddingBottom="15dip"     
      android:paddingLeft="0dip"     
      android:paddingRight="0dip" 
      android:paddingTop="0dip" >
 
    <TextView 
           android:id="@+id/dialogTitle"         
           android:layout_width="fill_parent" 
           android:layout_height="wrap_content" 
           android:layout_marginTop="20dip" 
           android:background="#00000000"         
           android:gravity="center" 
           android:text=""         
           android:textColor="#fff" 
           android:textSize="22sp" 
           android:textStyle="bold" >
   </TextView>
    <TextView 
          android:id="@+id/dialogMessage"         
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content"         
          android:layout_below="@+id/dialogTitle"         
          android:focusable="true" 
          android:focusableInTouchMode="true"         
          android:gravity="center"         
          android:maxLines="10"         
          android:padding="10dip" 
          android:scrollbars="vertical" 
          android:text="" 
          android:textColor="#fff"         
          android:textSize="18sp" >
    </TextView>
    <Button         
          android:id="@+id/OkButton" 
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content"         
          android:layout_below="@+id/dialogMessage" 
          android:layout_centerHorizontal="true" 
          android:layout_marginLeft="10dip" 
          android:layout_marginRight="10dip" 
          android:background="@drawable/button" 
          android:text="OK"         
          android:textColor="#FFFFFF" >
    </Button>
</RelativeLayout>
 
 
Button design in drawable xml file 
 
button.xml
 
<?xml version="1.0" encoding="utf-8"?><selector xmlns: 
android="http://schemas.android.com/apk/res/android"
 
<item android:state_pressed="true" 
 android:drawable="@drawable/button_bg_pressed" /> 
<!-- pressed -->     
<item android:state_focused="true"  
android:drawable="@drawable/button_bg_pressed" />
 <!-- focused --> 
 <item android:drawable="@drawable/button_bg_normal" /> 
<!-- default --> 
</selector> 
 
 Images 
 



 


Result Activity: