Monday 21 July 2014

Android - Reading images from assets file




Hi all here is my first blog, I am really exited. Here is my first Android application example.

MainActivity.java file

public class MainActivity extends ActionBarActivity {

@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ImageView image = (ImageView) findViewById(R.id.image);

try {
Drawable d = Drawable.createFromStream(getAssets().open("ic_launcher.png"), null); // here I am calling my image from asset file

image.setBackgroundDrawable(d);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

and our layout file will be activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.nktech.assetimagereader.MainActivity" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
 
    <ImageView
        android:id="@+id/image"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@+id/text"/>

</RelativeLayout>

android in asset file I have ic_launcher.png image file (assets/ic_laucher.png)

2 comments:

  1. Great dude, explain in brief about each file :)

    ReplyDelete
    Replies
    1. Hey thank you.:), After this I will represent my blog in better way.

      Delete