setImageDrawable vs setImageResource vs setBackground

Example show usage of setImageDrawable(), setImageResource(), setBackgroundDrawable(), setBackgroundResource and setBackground().

package com.example.androidsetimage;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

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

ImageView image1 = (ImageView)findViewById(R.id.image1);
ImageView image2 = (ImageView)findViewById(R.id.image2);
ImageView image3 = (ImageView)findViewById(R.id.image3);
TextView text4 = (TextView)findViewById(R.id.textview4);
Button button5 = (Button)findViewById(R.id.button5);
EditText edittext6 = (EditText)findViewById(R.id.edittext6);

image1.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
image2.setImageResource(R.drawable.ic_launcher);

//Requires API 16
image3.setBackground(getResources().getDrawable(R.drawable.ic_launcher));

//deprecated
text4.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_launcher));

button5.setBackgroundResource(R.drawable.ic_launcher);

//Requires API 16
edittext6.setBackground(getResources().getDrawable(R.drawable.ic_launcher));
}

}


<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#303030"
android:textStyle="bold|italic"
android:text="lesapplication.blogspot.com" />
<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/image2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/image3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/textview4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 4"/>
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 5"/>
<EditText
android:id="@+id/edittext6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Hello android-coding"/>

</LinearLayout>



0 Response to "setImageDrawable vs setImageResource vs setBackground"

Posting Komentar