RSS

Tag Archives: Android

Customising the ViewPager


So we found out how to use the ViewPager here and so next is how to customise the ViewPager indicator to match with your app’s theme – all the colors and stuff. If you haven’t already, please check the previous blog post. This is the continuation

We are going to build a style, which we will reference in the manifest as the Activity’s theme.

  1. Go to the values folder in you project  and add the following entry
  2. <resources>
        <style name="StyledIndicators" parent="@android:style/Theme.Light.NoTitleBar">
            <item name="vpiTabPageIndicatorStyle">@style/CustomTabPageIndicator</item>
        </style>
        
        <style name="CustomTabPageIndicator" parent="Widget.TabPageIndicator">
            <item name="android:background">@drawable/custom_tab_indicator</item>
            <item name="android:textColor">#FF555555</item>
        </style>
    
    </resources>
    
  3. in the drawable folder (any of them drawable – hdpi, mdpi…) add a new xml known as custom_tab_indicator.xml as referenced above
  4. <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <!-- Non focused states -->
        <item android:drawable="@drawable/custom_tab_indicator_unselected" android:state_focused="false" android:state_pressed="false" android:state_selected="false"/>
        <item android:drawable="@drawable/custom_tab_indicator_selected" android:state_focused="false" android:state_pressed="false" android:state_selected="true"/>
    
        <!-- Focused states -->
        <item android:drawable="@drawable/custom_tab_indicator_unselected_focused" android:state_focused="true" android:state_pressed="false" android:state_selected="false"/>
        <item android:drawable="@drawable/custom_tab_indicator_selected_focused" android:state_focused="true" android:state_pressed="false" android:state_selected="true"/>
    
        <!-- Pressed -->
        <!-- Non focused states -->
        <item android:drawable="@drawable/custom_tab_indicator_unselected_pressed" android:state_focused="false" android:state_pressed="true" android:state_selected="false"/>
        <item android:drawable="@drawable/custom_tab_indicator_selected_pressed" android:state_focused="false" android:state_pressed="true" android:state_selected="true"/>
    
        <!-- Focused states -->
        <item android:drawable="@drawable/custom_tab_indicator_unselected_pressed" android:state_focused="true" android:state_pressed="true" android:state_selected="false"/>
        <item android:drawable="@drawable/custom_tab_indicator_selected_pressed" android:state_focused="true" android:state_pressed="true" android:state_selected="true"/>
    
    </selector>
    

The images are here. Download them and place in your drawable folder. You can photoshop them to get the right color you want.

Lastly at the manifest, add the following theme in your activity tag.

 android:theme="@style/StyledIndicators"

And So you should have:

 <activity
            android:name=".MainActivity"
             android:theme="@style/StyledIndicators"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Here is a screenshot.

 
2 Comments

Posted by on September 28, 2012 in Android, Android tutorials, Code

 

Tags: , , ,

The ViewPager

So this is the first on the series on android open source libraries that I have come across. The ViewPager is used in alot of apps. It allows you to swipe across the screen to change the layout or move to the next page, sort of like tabs but not really. Its used in alot of apps, Google play store app uses it.

Im going to use Jake Wharton ViewPagerIndicator. 

  1. Go over to Git here or at the site, then look for a download button. Its going to a zip folder, unzip somewhere you will remember (in your worlkspace is good).
  2. Open eclipse, in your workspace, go to file -> Import. A dialog box will appear prompting you, under android select ‘Existing Android Code into Workspace’
  3. Browse into the folder you just unzipped and select ‘library’
  4. (I kno I skipped a number). Click ok and ok again in the next dialog.
  5. Start up your android project if you havent already. Now at the Project Explorer on your left, Right click on the folder of your application and choose properties. It should take you to this dialog. Choose android on the left.
  6.  Click on the ‘Add’ button then choose Library – the folder we imported into your workspace.
  7. If you are getting an error – “Found 2 versions of android-support-v4.jar in the dependency list but not all the versions are identical (check is based on SHA-1 only at this time).”. Go over to your ‘libs’ folder and replace android-support-v4.jar file with that in the library project you imported. Go to Project -> Clean.

We are now good to go. There are two things involved here: a ViewPager and an Indicator. The ViewPager is the main page while the indicator is sort of like the tab (in this case).

    1. In your project add a new xml file. (main_activity.xml – it was the default)
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.viewpagerindicator.TabPageIndicator
        android:id="@+id/indicator"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        />
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />
</LinearLayout>
    1. Also create xml file – one or more that will be the different pages that a user can swipe through
<!-- page.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title"
        android:textAppearance="?android:attr/textAppearanceLarge" />
<a href="https://mycodeandlife.wordpress.com/wp-content/uploads/2012/09/device-2012-09-27-204357.png"><img src="https://mycodeandlife.wordpress.com/wp-content/uploads/2012/09/device-2012-09-27-204357.png?w=200" alt="" title="device-2012-09-27-204357" width="200" height="300" class="aligncenter size-medium wp-image-300" /></a>
    <TextView
        android:id="@+id/tvdesc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Description" />

</LinearLayout>

On the java side we have MainActivity.java

package com.gilo.viewpagerexample;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.viewpagerindicator.TabPageIndicator;

public class MainActivity extends Activity{
        //these are the titles that will appear on the "tabs"
	final String[] page_titles = new String[]{"Home", "Me", "Apps", "Android", "About"};
	//this will go the description TextView
        final String[] desc = new String[]{
			"This is the homepage the first one you will see.",
			"I'm pretty much me for now I run this really cool blog you should check it out at mycodeandlife.wordpress.com",
			"I build appps mostly for fun. If you ever want an app just holla",
			"This is the android section",
			"This blog is my journal through life in code and development"
	};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Instantiating the adapter
        GiloAdapter mAdapter = new GiloAdapter(this);

        //instantiate the Views
        ViewPager mPager = (ViewPager)findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);

        TabPageIndicator mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
        mIndicator.setViewPager(mPager);
    }

    private class GiloAdapter extends PagerAdapter{

    	Context context;

    	public GiloAdapter(Context c){
    		this.context = c;
    	}

    	//This is the number of pages -- 5
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return page_titles.length;
		}

		@Override
		public boolean isViewFromObject(View v, Object o) {
			// TODO Auto-generated method stub
			return v.equals(o);
		}

		//This is the title of the page that will apppear on the "tab"
		public CharSequence getPageTitle(int position) {
            return page_titles[position];
        }

		//This is where all the magic happen
		public Object instantiateItem(View pager, int position) {
			final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    		View v = inflater.inflate(R.layout.page, null, false);

    		TextView title = (TextView)v.findViewById(R.id.tvTitle);
    		TextView description = (TextView) v.findViewById(R.id.tvdesc);

    		title.setText(page_titles[position]);
    		description.setText(desc[position]);

    		//This is very important
    		( (ViewPager) pager ).addView( v, 0 );

    		return v;
		}

    	@Override
    	public void destroyItem(View pager, int position, Object view) {
    		((ViewPager) pager).removeView((View) view);
    	}

    	@Override
    	public void finishUpdate(View view) {
    	}

    	@Override
    	public void restoreState(Parcelable p, ClassLoader c) {
    	}

    	@Override
    	public Parcelable saveState() {
    		return null;
    	}

    	@Override
    	public void startUpdate(View view) {
    	}

    }

}

The ViewPage takes an Adapter in this case I’ve written GiloAdapter. The most important method is instantiateItem(View pager, int position) which selects which Layoout to use. I used a LayoutInflator but with only one Layout.(The current library uses fragments). If you are familiar with Adapters from ListViews then its almost the same idea. The destroyItem() is also important that you override or your app will force close with weird error messages.

Lastly we are going to use the default style in the library, so in the manifest add this in the manifest in your Activity tag:

android:theme="@style/Theme.PageIndicatorDefaults"

The .MainActivity in my app

<activity
            android:name=".MainActivity"
             android:theme="@style/Theme.PageIndicatorDefaults"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

And we have

Thats it, next blogposts we’ll change the colors(customise), maybe look at another indicator.
Drop a comment if you found this helpful or if you got some error you can’t figure out, and I’ll try and have a look.

 
12 Comments

Posted by on September 27, 2012 in Android, Android tutorials, Code

 

Tags: , , , ,

Fonts

TextView and views and Buttons have a method setTpeface that allows you to set a font. But first download a font or if you already have one thats alright. Place the font file (.otf , .ttf) into the assets folder of your project.

We create a font object by accessing the assets folder. So at the onCreate method (or just when you want it):

Typeface font = Typeface.createFromAsset(this.getAssets(),"AnnabelScript.ttf");

Make sure you have the full name of the font including the extension.

Next just apply the font to the Views that you want.


        TextView tv1 = (TextView) findViewById(R.id.textView1);
        TextView tv2 = (TextView) findViewById(R.id.textView2);
        TextView tv3 = (TextView) findViewById(R.id.textView3);
        TextView tv4 = (TextView) findViewById(R.id.textView4);
       
        tv1.setTypeface(font);
        tv2.setTypeface(font);
        tv3.setTypeface(font);
        tv4.setTypeface(font);

The whole page:

package com.example.myblog;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        TextView tv1 = (TextView) findViewById(R.id.textView1);
        TextView tv2 = (TextView) findViewById(R.id.textView2);
        TextView tv3 = (TextView) findViewById(R.id.textView3);
        TextView tv4 = (TextView) findViewById(R.id.textView4);
        
        Typeface font = Typeface.createFromAsset(this.getAssets(),"AnnabelScript.ttf");
        
        tv1.setTypeface(font);
        tv2.setTypeface(font);
        tv3.setTypeface(font);
        tv4.setTypeface(font);
    }
    
}

 
Leave a comment

Posted by on September 7, 2012 in Android, Android tutorials, Code

 

Tags: , ,

A Cool Photo Gallery

The end-result is

Starting at the xml, create a new xml file. This xml file will contain a listview.

gallery.xml


<!---gallery.xml--->

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/bag_cake"
     >
     <ListView
            android:id="@+id/lvdata"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_marginBottom="1dp"
            android:layout_weight="1"
            android:cacheColorHint="#251e1b" android:layout_marginTop="1dp">
        </ListView>
    

</LinearLayout>

Next the row-item. This will be used by the photoAdapter and define how each row item should be placed.

row_photo.xml

<?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="wrap_content" >



    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:layout_weight="1" >


        <ImageView
            android:id="@+id/iv1"
            android:layout_width="80dp"
            android:layout_height="fill_parent"
            android:layout_margin="2dp"
            android:layout_weight="0.25"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher" />


        <ImageView
            android:id="@+id/iv2"
            android:layout_width="80dp"
            android:layout_height="fill_parent"
            android:layout_margin="2dp"
            android:layout_weight="0.25"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher" />


        <ImageView
            android:id="@+id/iv3"
            android:layout_width="80dp"
            android:layout_height="fill_parent"
            android:layout_margin="2dp"
            android:layout_weight="0.25"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher" />


        <ImageView
            android:id="@+id/iv4"
            android:layout_width="80dp"
            android:layout_height="fill_parent"
            android:layout_margin="2dp"
            android:layout_weight="0.25"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher" />

    </LinearLayout>

</LinearLayout>

Thats it for the xml. There java files, one that defines the row as an object(Photo class), the PhotoAdapter Class and the implementation – (Gallery.java).

Photo.java

package com.gilo.zosi;

public class Photo {
	private int iv1;
	private int iv2;
	private int iv3;
	private int iv4;

	public Photo(int iv1, int iv2, int iv3, int iv4) {
                //The constructor takes the ids of three images and initiliases them
		super();
		this.iv1 = iv1;
		this.iv2 = iv2;
		this.iv3 = iv3;
		this.iv4 = iv4;
	}

	public int getIv1() {
		return iv1;
	}

	public void setIv1(int iv1) {
		this.iv1 = iv1;
	}

	public int getIv2() {
		return iv2;
	}

	public void setIv2(int iv2) {
		this.iv2 = iv2;
	}

	public int getIv3() {
		return iv3;
	}

	public void setIv3(int iv3) {
		this.iv3 = iv3;
	}

	public int getIv4() {
		return iv4;
	}

	public void setIv4(int iv4) {
		this.iv4 = iv4;
	}

}

and for PhotoAdapter.java

package com.gilo.zosi;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class PhotoAdapter extends BaseAdapter {
	private ArrayList<Photo> list;
	private LayoutInflater mInflater;

	public PhotoAdapter(Context context, ArrayList<Photo> list) {
		this.list = list;
		this.mInflater = LayoutInflater.from(context);
	}

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

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

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.row_photo, null);
			holder = new ViewHolder();
			holder.iv1 = (ImageView) convertView.findViewById(R.id.iv1);
			holder.iv2 = (ImageView) convertView.findViewById(R.id.iv2);
			holder.iv3 = (ImageView) convertView.findViewById(R.id.iv3);
			holder.iv4 = (ImageView) convertView.findViewById(R.id.iv4);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.iv1.setImageResource(list.get(position).getIv1());
		holder.iv2.setImageResource(list.get(position).getIv2());
		holder.iv3.setImageResource(list.get(position).getIv3());
		holder.iv4.setImageResource(list.get(position).getIv4());
		return convertView;
	}

	private static class ViewHolder {
		private ImageView iv1, iv2, iv3, iv4;
	}
}


package com.gilo.zosi;

import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class Gallery extends Activity{

	ListView gallery;
	ArrayList<Photo> row = new ArrayList<Photo>();

	protected void onCreate(Bundle icicle){
		super.onCreate(icicle);
		setContentView(R.layout.gallery);
		
		gallery = (ListView) findViewById(R.id.lvdata);
		
		init();
		
		gallery.setAdapter(new PhotoAdapter(getBaseContext(), row));
	}
	
	private void init(){
		
		Photo p1 = new Photo(R.drawable.p1, R.drawable.p2, R.drawable.p3, R.drawable.p4);
		Photo p2 = new Photo(R.drawable.p5, R.drawable.p6, R.drawable.p7, R.drawable.p8);
		Photo p3 = new Photo(R.drawable.p9, R.drawable.p10, R.drawable.p11, R.drawable.p12);
		
		row.add(p1);
		row.add(p2);
		row.add(p3);
		row.add(p2);
		row.add(p1);
		row.add(p3);
		row.add(p2);
		
		
	}
}

 
2 Comments

Posted by on September 6, 2012 in Uncategorized

 

Tags: , , , ,

Android Custom dialogs

We are gonna try make something like this:

First off, start with the xml side of it. Open a new xml file in the layout folder. Name it something. It is in this xml file that we are going to design how it will look. Here is the xml for this one:

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

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:orientation="horizontal" >
		
        <!-- This is for the info image -->
        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:src="@android:drawable/ic_menu_info_details" />

        <!-- Title -->
        <TextView
            android:id="@+id/tvmessagedialogtitle"
            android:layout_width="184dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="4dip"
            android:layout_weight="0.01"
            android:padding="8dp"
            android:text="Message"
            android:textColor="#343434"
            android:textSize="16dip"
            android:textStyle="normal"
            android:typeface="normal" />
    </LinearLayout>

    <!-- Underline with this bluish color -->
    <View
        android:layout_width="fill_parent"
        android:layout_height="2dip"
        android:background="#09adb9" />

    <!-- The message -->
    <TextView
        android:id="@+id/tvmessagedialogtext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="4dip"
        android:gravity="left"
        android:padding="8dp"
        android:text="Message"
        android:textColor="#343434"
        android:textSize="15dip"
        android:textStyle="normal"
        android:typeface="normal" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:orientation="horizontal" >

        <!-- Yes button -->
        <Button
            
            android:id="@+id/bmessageDialogYes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dip"
            android:layout_marginLeft="60dp"
            android:background="#ffffff"
            android:padding="8dp"
            android:text="Yes"
            android:textColor="#343434"
            android:textSize="13dip"
            android:textStyle="normal"
            android:typeface="normal" />

        <!-- No Button -->
        
        <Button
            android:id="@+id/bmessageDialogNo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dip"
            android:layout_marginLeft="80dp"
            android:background="#ffffff"
            android:padding="8dp"
            android:text="No"
            android:textColor="#343434"
            android:textSize="13dip"
            android:textStyle="normal"
            android:typeface="normal" />
    </LinearLayout>

</LinearLayout>

By default, dialogs are set to come with a title, even when none is defined it still gives this blank grey area thats not cool at all. So we want to get rid of that. Ive got to say I found this at stackoverflow.com, I dont remember who it was, but I’m still going to give him/her credit here.
So go over to the res folder, under it there is a values folder then open styles.xml. Add the following entry between the tags.

<style name="FullHeightDialog" parent="android:style/Theme.Dialog">
   <item name="android:windowNoTitle">true</item>
	</style>

Now over at the java side:

Dialog dialog = new Dialog(this, R.style.FullHeightDialog); //this is a reference to the style above
dialog.setContentView(R.layout.yesnomessage); //I saved the xml file above as yesnomessage.xml
dialog.setCancelable(true);

//to set the message
TextView message =(TextView) dialog.findViewById(R.id.tvmessagedialogtext);
message.setText("You are about to call " + num + ". Are you sure you want to call?");

//add some action to the buttons
            String num = "0123456789"
            yes = (Button) dialog.findViewById(R.id.bmessageDialogYes);
            yes.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					Intent callIntent = new Intent(Intent.ACTION_CALL);
					callIntent.setData(Uri.parse("tel: " + num));
					dialog.dismiss();
					startActivity(callIntent);
					
				}
			});
            
            no = (Button) dialog.findViewById(R.id.bmessageDialogNo);
            no.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					dialog.dismiss();
				}
			});
           
            dialog.show();

Thats it, so this is sort of the interface to my earlier blogpost on how to make a phone call from the app. If the user presses yes on the dialog it starts up an Intent that is passed to the phone app which is launched.

Till again….

 
1 Comment

Posted by on August 16, 2012 in Android, Android tutorials, Code

 

Tags: , , ,

Android animating buttons

Create an xml file in the drawable folder and select the root element as “selector”.

<?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/toast"
        >
    </item>
     <item 
        android:state_focused="true"
        android:drawable="@drawable/smart"
        >
    </item>
    
      <item 
        android:drawable="@drawable/looking"
        >
    </item>

</selector>

In the layout xml file let the background of the button refer to the above xml:

<Button
        android:id="@+id/badd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/custom" />

And now you have something that looks like:

When highlighted(focused):

And when you click on it:

 
 

Tags: , ,

Android Preferences

Hey, I checked on the preferences in android. A blog post ago I made a menu that would allow for someone to set his/her preferences.One cool thing about Preferences is that whatever values stored in them will not be lost even after exiting the app. So values like the persons name and if the user was fed up with our music and set it off and other stuff are always good to remember each time the user starts the app.

First off, I created a new folder to keep all the preferences. Its worth noting that,  though prefs.xml is an  xml file but this is will contain Preferences as opposed to the usual ones containing the layout. Created the prefs.xml, or whatever you want to  name it. And in the prefs.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    
	<EditTextPreference 
	    android:title="Name"
	    android:key="name"
	    android:summary="Enter your name: "
	    />
	
	<CheckBoxPreference 
	    android:title="Sound"
	    android:defaultValue="true"
	    android:key="sound"
	    android:summary="Check to have sound"
	    />
	
	<ListPreference 
	    android:title="Options"
	    android:key="options"
	    android:summary="Choose one of the options"
	    android:entries="@array/list"
	    android:entryValues="@array/values"
	    />
    
</PreferenceScreen>

The ListPreference gets values from an array set up in an xml file called array in the values folder. The array.xml looks like:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    
	<EditTextPreference 
	    android:title="Name"
	    android:key="name"
	    android:summary="Enter your name: "
	    />
	
	<CheckBoxPreference 
	    android:title="Sound"
	    android:defaultValue="true"
	    android:key="sound"
	    android:summary="Check to have sound"
	    />
	
	<ListPreference 
	    android:title="Options"
	    android:key="options"
	    android:summary="Choose one of the options"
	    android:entries="@array/list"
	    android:entryValues="@array/values"
	    />
    
</PreferenceScreen>

And the java file for this (notice the difference as this isn’t a layout xml but preference)

package com.learning.gilo;

import android.os.Bundle;
import android.preference.PreferenceActivity;
//it extends PreferenceActivity and not Activity as we've been doing
public class Prefs extends PreferenceActivity{
	protected void onCreate(Bundle b){
		super.onCreate(b);
		//This will add the preferences from prefs.xml
		addPreferencesFromResource(R.xml.prefs);
		
	}

}

In the menu we are going to start an intent when the preference item is clicked that will start Prefs activity.

public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch(item.getItemId()){
		case R.id.about:
			Intent i = new Intent("com.learning.gilo.ABOUTUS");
			startActivity(i);
			
			break;
		case R.id.exit:
			finish();
			break;
		case R.id.preferences:
			//This will start the Prefs activity
			Intent p = new Intent("com.learning.gilo.PREFS");
			startActivity(p);
			break;
		
		}
		
		return false;
	}

 

 

 
1 Comment

Posted by on July 4, 2012 in Android, Android tutorials, Code

 

Tags:

Android Displaying text using a theme.Dialog

I added afew stuff to the Menu(Check out the menu first if you haven’t ), now when you click on “About” it show this dialog box. Its basically implemented using an xml file containing a Text View:

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello there I'm Gilbert currently(7/2/2012) a student at JKUAT Taita Taveta campus first year and this are my chronicles"

        />

</LinearLayout>

and a Java class that will have its setContentView() to the xml above:


package com.learning.gilo;

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

public class AboutUs extends Activity{

	protected void onCreate(Bundle b){
		super.onCreate(b);
		setContentView(R.layout.aboutus);
	}
}

Now at the main class the method that shall detect which item is selected is:

public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch(item.getItemId()){
		case R.id.about:
			Intent i = new Intent("com.learning.gilo.ABOUTUS");
			startActivity(i);

			break;
		}

BUT, the magic code that will start this activity as a Dialog is in the Android manifest:


<activity
            android:name=".AboutUs"
            android:label="About me"
            android:theme="@android:style/Theme.Dialog"
             >
            <intent-filter>
                <action android:name="com.learning.gilo.ABOUTUS" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

Its this part:

android:theme="@android:style/Theme.Dialog"
 
 

Tags:

Creating a menu

A menu is the component that pops up when you press the menu button. The design of the menu is held as an xml and then implemented in java. So to do it, I created a separate folder known as menu that will contain the menu files ie nice_menu.xml. Eclipse automatically detects that you are creating a menu and when you create a new xml it will open a file that looks something like this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:title="About"
android:id="@+id/about"
/>
<item
android:title="Preference"
android:id="@+id/preferences"
/>
<item
android:title="Exit"
android:id="@+id/exit"
/>

</menu>

<item /> adds a label like the preferences or exit. The id is so that you can reference in java and add methods to detect when that particular option has been selected. There are more stuff here, Its a great read like you could add icons, I’ll do that in the next blog post along with the method that detects which item has been selected. For now the menu does nothing when clicked.

Going to the java side of this. We need to inflate the menu (show the menu on screen). You have to implement the onCreateOptionsMenu(Menu).

public boolean onCreateOptionsMenu(Menu menu){
		super.onCreateOptionsMenu(menu);
		MenuInflater showMenu = getMenuInflater();
		showMenu.inflate(R.menu.nice_menu, menu);

		return true;
	}

To view the complete source code for the camera app with menu included: Click here

 
2 Comments

Posted by on July 1, 2012 in Android, Code

 

Tags: ,

Making a toast

One of the components that android phones come with is the Toast. It sort of gives information to the user about something, just like in the above case. Its supposed to inform us that the wallpaper has been set. It’s really reassuring, I gotta say. Ok so, there are a few ways you can do it (its really one way actually but you’ll see):

Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,"This is a toast that will say: Wallpaper set",duration);
toast.show();

or

Toast.makeText(getApplicationContext(), "This is a toast that will say: Wallpaper set", Toast.LENGTH_LONG).show();

So as you can see its the Toast.makeText() that builds the toast. It takes three parameters: the context, text to be displayed and the duration of display. You can still make custom toast that display images and other stuff as opposed to text alone. So watch out for this space.

click here to view the full app code.

 
1 Comment

Posted by on June 27, 2012 in Android, Android tutorials, Code

 

Tags: