Tuesday, June 19, 2012

Part1 : Useful Eclipse Templates for Android Development

I normally setup eclipse templates for repeat coding fragments. If you are not aware of eclipse editor templates, just a small example: just open a java code file and type "syso" (shortcut name) and press Ctrl+space then you will see all  "System.out.println();" will be inserted by eclipse for you.
To see all existing templates and its shortcut open your eclipse, open the window menu and click on Preference. Inside the Preference dialog , navigate to Java --> Editor --> Templates, Now you see full list there. (Eclipse-->Window-->Preference-->Java-->Editor-->Templates)
You can add your own templates there and make use of them in your coding and make your coding fast. Just click "New.." button, fill the "New Template" Dialog and OK.

1. In android, in case if we want to get logs we want to insert "Log.i" statements with proper message. This template will be useful for that.

Name: alog
Context: Java statements
Description: android log statement
Pattern: Log.i(TAG,"::${enclosing_method}:"+"${cursor}");

Now,For Example, in side onCreate  if you type alog and press Ctrl+space you will get:
Log.i(TAG, "::onCreate:" + ""); 

2. In #1 you see, we have to pass a TAG, normally this should be the Class name of the method we define in the top. I used to go for a full qualified name of any class. Sometime this will be useful in case of Custom Views to copy its name to crate layout XML files.


Name: atag
Context: Java type members
Description: android log tag
Pattern: 

@SuppressWarnings("unused")
private static final String TAG = "${enclosing_package}.${enclosing_type}";


Ex: @SuppressWarnings("unused")
private static final String TAG = "demo.DemoAcitity";


3. Inside the activity most we have to find View By Id and call some method on it.


Name: afind
Context: Java
Description: android find view
Pattern: 

${type} ${new_name} = (${type})findViewById(R.id.${cursor});

type afind and press Ctrl+Space, then you will get:
type| new_name = (type)findViewById(R.id.);

for example if that is a button then, type Button or But and press Ctrl+Space then you will get:
Button new_name = (Button)findViewById(R.id.);

Then press Tab cursor will move to new_name
Button new_name = (Button)findViewById(R.id.);

Type the name you want for the variable, then press Tab cursor will move after ".id.":
Button button = (Button)findViewById(R.id.|);
The just press Ctrl+space and choose the id from the list.

So you will end as follows:
Button button = (Button)findViewById(R.id.btn_add);

In android we mostly do this in onCreate method and assign to member variable. and refer from other method. Now you right click on the variable name choose Refactor  and choose "Convert Local Variable to Field" this will create a Field for you.


here i have uploaded the template file.

Part 2 : Useful Eclipse Templates for Android Development

No comments: