Sunday, November 15, 2009

Creating EditText Programmatically in Android

In this tutorial, I am going to explain how to create a EditText programatically, and the different properties, that we can assign to it in Android.

If we want, our EditText to take only numbers. Then the code is,


edit.setInputType(InputType.TYPE_CLASS_NUMBER);


For password style implementation, for the editText, the code is,


edit.setTransformationMethod(new android.text.method.PasswordTransformationMethod()
.getInstance());


For putting, all letters in caps, the code


InputFilter[] filter = new InputFilter[1];
filter[0] = new InputFilter.AllCaps();
edit.setFilters(filter);


For restricting, only upto this much characters to enter in the editText, the code is,


InputFilter[] filter = new InputFilter[1];
filter[0] = new InputFilter.LengthFilter(15);
edit.setFilters(filter);


In this, I am restricting the characters upto 15 characters.

For moving the editText horizontally or vertically, the code is,


edit.post(new Runnablepublic void run() {
edit.offsetLeftAndRight(50);
edit.offsetTopAndBottom(100);
}
});

Tuesday, November 10, 2009

Creating Menu & SubMenu in Android

In this tutorial, I am going to explain, how to create options menu, subMenu etc..

From Activity class, just override the method, onCreateOptionsMenu(). Then inside the method, create the menu, according to our wish.

Then, override another method called, onOptionsItemSelected. In this, if we select any, menu, what we have to do, will code in this. That means, menu events will be handled in this method.


public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case 0: Toast.makeText(this, "clicked Menu 1",
Toast.LENGTH_SHORT).show();
break;
case 1: Toast.makeText(this, "clicked Menu 2",
Toast.LENGTH_SHORT).show();
break;
case 2: Toast.makeText(this, "clicked Menu 3",
Toast.LENGTH_SHORT).show();
break;
}
return true;
}



The screenshot will be look like this.



For adding submenu, we have to use the function called addSubMenu(), in the Menu class

the code is,


public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SubMenu sub = menu.addSubMenu(0,1,0, "SubMenu");
sub.add(0,11,0,"SubMenu 1");
sub.add(0,12,0,"SubMenu 2");
sub.add(0,13,0,"SubMenu 3");
return true;
}



The screen shot of this is like this..



When click in the sub menu, we will see the screen like this..


Androidians