Wednesday, March 5, 2014

Set color of Android button, programmatically

Here's a little problem that had Nirmal frustrated. If there is a layout with multiple buttons to switch layouts or views, how can the user be shown which layout he/she/ze is currently viewing? One idea: change the color of the text on the button which corresponds to the current layout. To do that is so easy!

Button whateverButton = (Button) findViewById(;
whateverButton.setTextColor(Color.parseColor("#00a2ff")); //set text color

of course, you will need to import Button and Color if you haven't already, in Eclipse

How to swipe between layouts in Android apps

Is it easy to open a new layout by swiping horizontally? Yes, it is. When you want to drag your fingers across the screen to switch view layouts, just follow this code!

First, import the Android support library. Right click on your project in ecplise, go to Android Tools, then select Add Support Library. If you don't see that, go to your SDK manager under the Window menu, and find and download it! Now we have all the resources we need.

Paste this in your oncreate to set up the horizontal swipe:
   MyPagerAdapter adapter = new MyPagerAdapter();
   ViewPager pager = (ViewPager) findViewById(;
//set the opening screen
Add this class somewhere after the oncreate:
 public class MyPagerAdapter extends PagerAdapter {
    public int getCount() {
        return 2; //set  number of swipe screens here 
    public Object instantiateItem(final View collection, final int position) {
        LayoutInflater inflater = (LayoutInflater collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        int resId = 0;
        switch (position) {
        case 0:
            resId =; //set which layout will show on load
        case 1:
            resId = R.layout.subway; //what layout swiping shows                 break;
        View view = inflater.inflate(resId, null);
        ((ViewPager) collection).addView(view, 0);
        return view;
    public void destroyItem(final View arg0, final int arg1, final Object arg2) {
         ((ViewPager) arg0).removeView((View) arg2);
    public boolean isViewFromObject(final View arg0, final Object arg1) {
        return arg0 == ((View) arg1);


And put this in the default layout, which is actually never seen because it gets replaced with the first swipe screen
        android:layout_height="match_parent" />