Wednesday, 4 September 2013

Write Code for Different Android Versions in Your App

Fragmentation has been a big issue in Android since the beginning and everyone has different views about it. I personally don't think that there is an effective way to avoid fragmentation at the rate Android is growing at. 

it's actually not that hard to write code that handle different Android versions inside your application. I know, we can always publish different apks to handle different android versions, but this may not be the optimal choice in all cases. So, here is little code snippet showing how to handle fragmentation to a certain extent in Android:

 @SuppressLint("NewApi")  
  @Override  
  public boolean onCreateOptionsMenu(Menu menu) {  
  MenuInflater inflater = getMenuInflater();  
  inflater.inflate(R.menu.menu, menu);  
  return true;  
  }  

The above code is just a simple example, that shows how you can create different menu options for different Android versions.

Now you will have the question in mind that which will better between @SuppressLint 'NewApi' and @TargetApi(GINGERBREAD)

Answer is @TargetApi amd @SuppressLint have the same core effect: they suppress the Lint error.


The difference is that with @TargetApi, you declare, via the parameter, what API level you have addressed in your code, so that the error can pop up again if you later modify the method to try referencing something newer than the API level cited in @TargetApi.


Happy Coding.....:)

2 comments: