Thursday, August 16, 2012

ViewFlipper and SlidingDrawer example Android


In my last post i talked about android selector mechanism and how to customize default GUI components apperances. another issue with mobile phone applications is limited displaying space, i mean if your application wants to go a bit further than a basic , simple application, it is almost gonna be impossible to fit all GUI options and features in a relatively small displaying space of mobile phones.

as we've already talked about it, the first option to solve this sort of problems is Menus and dialogs which are pretty easy to use and simple, but what if you need something more than that with higher level of customizability, that's whenViewFlipper and SlidingDrawer come into play(although they could be used for other purposes as well), like menus and dialogs they enable us to have some views hidden and show them when they are requested or when it's appropriate.



first of all let's see what a ViewFlipper is, ViewFlipper is Actually a View container which can hold different Views, but it shows just one of those Views at a time and hide others, you can switch between views manually or automatically, most interesting thing about ViewFlipper is that it uses two different Animations for flipping between views, one is used for outgoing View and the other one for incoming View.


There are two views between which we wanna flip, a ListView (Which we talked about it last time) and a simple view with a text and a button on it, When we press "Next" button our ListView will slide out and the other view will slide in and when "Go Back" button is pressed two views will be switched again. 

our XML will be something like this : 

<ViewFlipper 
       android:id="@+id/flipper"
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent">
  <FrameLayout 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content"
       android:layout_gravity="top" 
       android:layout_marginTop="50dip">
    <ListView 
        android:id="@+id/list" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:dividerHeight="0dip"
        android:divider="@null" 
        android:listSelector="@drawable/list_selector"
        android:layout_gravity="center" /> 
  </FrameLayout>
  <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:orientation="vertical"
        android:background="@drawable/wood01" 
        android:padding="20dip"
        android:layout_gravity="top" 
        android:layout_marginTop="50dip">
     <TextView 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content"
          android:text="TEST" 
          android:layout_gravity="center" 
          android:padding="15dip"
          android:textSize="22dip" 
          android:textColor="@color/white" />
    <Button 
          android:text="Go Back" 
          android:id="@+id/back_btn"
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content" />
  </LinearLayout>
 </ViewFlipper>

As you can see our ViewFlipper has two children, a FrameLayout containing the ListView and a LinearLayout containing a TextView and a Button. by default the first child is shown when application comes up for the first time.

Setting Animation for our flipper is pretty easy and straigh forward, here's the code I've used :

  this.flipper = (ViewFlipper)findViewById(R.id.flipper);
        
  Animation s_in  = AnimationUtils.loadAnimation(this, R.anim.slidein);
  Animation s_out = AnimationUtils.loadAnimation(this, R.anim.slideout);
  this.flipper.setInAnimation(s_in);
  this.flipper.setOutAnimation(s_out);

and here are the content of slidein.xml and slideout.xml respectively : 

<?xml version="1.0" encoding="utf-8"?>
<set 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:interpolator="@android:anim/decelerate_interpolator">
    <translate 
        android:fromXDelta="-100%" 
        android:toXDelta="0%" 
        android:duration="1800" />    
</set>
<?xml version="1.0" encoding="utf-8"?>
<set 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:interpolator="@android:anim/decelerate_interpolator">     
    <translate 
        android:fromXDelta="0%" 
        android:toXDelta="100%" 
        android:duration="1800" />    
</set>

All you need to do to switch the showing view manually is to use showNext() and showPrevious() methods of ViewFlipper class.
Another predefined Widget for hiding stuff is SlidingDrawer and its name pretty much suggests what it does. what does a drawer do!? it has a handle which is used to drag the drawer container out...obviously ;)


First of all, I should say sorry for this wierd object I used for my drawer's handle ;) I couldn't find anything better!!
here is the XML which is being used to create what you saw above:

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="230dip" 
    android:id="@+id/frameLayout" 
    android:layout_gravity="bottom">
   <SlidingDrawer 
        android:layout_height="wrap_content"
        android:handle="@+id/handle" 
        android:content="@+id/content"
        android:id="@+id/slide" 
        android:orientation="vertical"
        android:layout_width="fill_parent">
   <ImageView 
        android:layout_width="55dip"
        android:layout_height="55dip" 
        android:id="@id/handle" 
        android:src="@drawable/arrow" />
  <LinearLayout 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:id="@id/content"
        android:orientation="vertical" 
        android:background="@drawable/wood01"
        android:padding="10dip">
     <Button 
         android:text="Test1" 
         android:id="@+id/Button01"
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content" />
     <Button 
         android:text="Test2" 
         android:id="@+id/Button02"
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content" />
     <Button 
         android:text="Test3" 
         android:id="@+id/Button03"
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content" />
   </LinearLayout>
  </SlidingDrawer>
</FrameLayout>

SlidingDrawer tag has two important attributes, android:handle and android:content; these attributes are actually references to other views which will be rendered as our drawer's handle and content. as you can see here we have two child views with the same id as specified for android:handle and android:content.

That's it. we are now familiar with two other useful Android widgets...

Custom selector android

GUI is always an important part of any application, because ordinary users dont know and don't care what's behind the scene; they want something easy to work with and nowadays attractive GUI is a must for most applications. although making an appealing and innovative interface needs something more than just programming skills and knowledge, every programmer should know how to customize different GUI components within whatever framework and environment they are working.

Today I'm gonna talk about one of the beautiful features of Android which gives you the ability to change the default behavior of GUI components. 
when designing GUIs, most of the times you want to change the appearance of buttons, input Fields, menus and.... Android Selectors have been provided to solve all these kind of problems, they enable us to decide what to show and how to show based on different states of each components...for example you can tell a button to have black background color with red text color when it is in pressed state or whatever else.

It is nothing but a simple ListView... believe me, and here is the XML which is being used to create it :

<ListView android:id="@+id/list" 
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" 
      android:dividerHeight="0dip"
      android:divider="@null" 
      android:listSelector="@drawable/list_selector"
      android:layout_gravity="center" />
the code which I've used to populate the list :

  ListView view = (ListView)findViewById(R.id.list);
  view.setAdapter(new ArrayAdapter(this, R.layout.menu_item, ITEMS));
  view.setOnItemClickListener(this); 
   
and finally, here is the content of menu_item.xml file :

<?xml version="1.0" encoding="utf-8"?>
 <TextView xmlns:android="http://schemas.android.com/apk/res/android" 
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:textSize="12dip"
           android:textStyle="bold"
           android:paddingTop="20dip"
           android:paddingBottom="20dip"
           android:layout_gravity="center" 
           android:gravity="center"
           android:background="@drawable/selector"
           android:textColor="@drawable/color_selector"/>: 

see? it's a simple, ordinary list, there is no secret here but a simple trick; I've used selectors for both background and text color for our TextView, what do you think "selector" and "color_selector" are?
they actually refer to selector.xml and color_selector.xml files inside drawable directory, you can see the content of them below : 


<selector xmlns:android="http://schemas.android.com/apk/res/android">:
    <item android:state_selected="true" android:drawable="@drawable/selector_s" />:
    <item android:state_pressed="true" android:drawable="@drawable/selector_s" />:
    <item android:drawable="@drawable/selector_d" />:  
</selector>:
<selector xmlns:android="http://schemas.android.com/apk/res/android">:
    <item android:state_selected="true" android:color="@color/black" />:
    <item android:state_pressed="true" android:color="@color/red" />:
    <item android:color="@color/white" />:  
</selector>:

what does the content of color_selector file mean? it says that the text color will be black in "selected" state, red in "pressed" state and white otherwise, and i reckon now you should be able to figure out what the content of selector file means. 
here is the content of selector_s and selector_d :

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/pill"
    android:gravity="center" />
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/pill_s"
    android:gravity="center" />

as you might have noticed,I've also used "listSelector" attribute of our ListView to customize the behavior of the list when user is going through options in the list. 
list_selector.xml file looks like this : 

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@drawable/wood01" />
    <item android:drawable="@drawable/wood02" />  
</selector> 

and here are all the drawable objects i used in this application if you wanna give it a try and see how easy it works ;)

Thursday, June 7, 2012

Creating and Writing into PDF file android



Creating and writing a data into the PDF file on SD Card. It works for me. Any queries comment down.

byte[]= bytes;

File createfile = new File("/sdcard/Acc/");
createfile.mkdirs();
File outputFile = new File(createfile, "Payslip.pdf");
try 
{
  FileOutputStream fos = new FileOutputStream(outputFile);
 bytes = Base64.decode(strBinaryString, Base64.DEFAULT);
 String filepath = "/sdcard/Acc/Payslip.pdf";
 OutputStream pdffos;
 pdffos = new FileOutputStream(filepath);
 pdffos.write(bytes);
 pdffos.flush();
 pdffos.close();
 } 
 catch (FileNotFoundException e) 
 {
    e.printStackTrace();
 } 
 catch (IOException e) 
 {
    e.printStackTrace();
 }

Tuesday, June 5, 2012

Android Application not working in 4.0 but working in 2.2


Today, my application crashed on Android 4 device. I always thought it will work on Android 4 because it was a simple application but I guessed wrong.

For some reason  getElementsByTagName  returns null in Android 4.0 or Android 3.0, if your  code look somewhat like this.


 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
 InputSource is = new InputSource(new StringReader("Some XML here and there"));
 Document document = builder.parse(is);
 Element root = document.getDocumentElement();
 root.normalize();
         
 NodeList items = root.getElementsByTagName("tag");  <-- this function will always return null on Android 4 


When i dig in I found a bug reported in Google forums. I found this very hard to believe because this is a very primary level issue and how did it get passed?

Anyway, As a work around I had to use XPath. Just remember to change the project's Android SDK to 2.2 or higher otherwise XPath classes are not visible. They resides in javax.xml.xpath namespace. Or you can use XmlPullParser which reads documents from top to bottom.


InputSource is = new InputSource(new StringReader("Some XML here and there"));
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
NodeList nodeList = (NodeList) xPath.evaluate("/xpath", is, XPathConstants.NOD
ESET);

Thursday, May 24, 2012

Android Emulator Properties

The downloadable platform includes the following emulator skins:


  • QVGA (240x320, low density, small screen)
  • WQVGA400 (240x400, low density, normal screen)
  • WQVGA432 (240x432, low density, normal screen)
  • HVGA (320x480, medium density, normal screen)
  • WVGA800 (480x800, high density, normal screen)
  • WVGA854 (480x854 high density, normal screen)
  • WXGA720 (1280x720, extra-high density, normal screen)
  • WSVGA (1024x600, medium density, large screen)
  • WXGA (1280x800, medium density, xlarge screen)
To test your application on an emulator that represents the latest Android device, you can create an AVD with the new WXGA720 skin (it's an xhdpi, normal screen device). Note that the emulator currently doesn't support the new on-screen navigation bar for devices without hardware navigation buttons, so when using this skin, you must use keyboard keys Home for the Home button, ESC for the Back button, and F2 or Page-up for the Menu button.
However, due to performance issues in the emulator when running high-resolution screens such as the one for the WXGA720 skin, we recommend that you primarily use the traditional WVGA800 skin (hdpi, normal screen) to test your application.

Wednesday, May 9, 2012

Simple Calendar control android


Hi developers, here the example for simple calendar control in android.

CalendarActivity .java


public class CalendarActivity extends Activity
{
 private EditText Calctrl;
 static final int DATE_DIALOG_ID = 0;
 final Calendar c = Calendar.getInstance();
 private int mYear, mMonth, mDay;
 private String sdate;
 private String[] arrayMonth = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   Calctrl = (EditText) findViewById(R.id.datepicker);
   mYear = c.get(Calendar.YEAR);
   mMonth = c.get(Calendar.MONTH);
   mDay = c.get(Calendar.DAY_OF_MONTH);
   sdate = currentDate(mYear, mMonth, mDay);
  Calctrl.setText(sdate);  

  Calctrl.setOnTouchListener(new OnTouchListener()
  {
   @Override
   public boolean onTouch(View v, MotionEvent event)
   {
    showDialog(DATE_DIALOG_ID);
    return true;
   }
  });
 }

 @Override
 protected Dialog onCreateDialog(int id)
 {
  switch (id)
  {
  case DATE_DIALOG_ID:
   return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,mDay);
  }
  return null;
 }

 @Override
 protected void onPrepareDialog(int id, Dialog dialog)
 {
  switch (id)
  {
  case DATE_DIALOG_ID:
   ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
   break;
  }
 } 

 private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
 {
  public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth)
  {
   mYear = year;
   mMonth = monthOfYear;
   mDay = dayOfMonth;
   String sdate = currentDate(mYear, mMonth, mDay);
   Calctrl.setText(sdate);
  }
 };

 private static String LPad(String schar, String spad, int len)
 {
  String sret = schar;
  for (int i = sret.length(); i < len; i++)
  {
   sret = spad + sret;
  }
  return new String(sret);
 }

 private String currentDate(int year, int month, int day)
 {
  String sdate = arrayMonth[month] + " " + LPad(day + "", "0", 2) + ", "+ year;
  return sdate;
 }
}
main.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="fill_parent"
    android:background="@drawable/app_background"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/datepicker"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:editable="false"
        android:inputType="none" />

</LinearLayout>