Androidでは、 “http://developer.android.com/reference/android/widget/ImageView.html[android.widget.ImageView]”クラスを使用して画像ファイルを表示できます。画像ファイルは使いやすいですが、Androidデバイスのさまざまな画面とdpiのために習得が難しいです。
このチュートリアルでは、dpiとさまざまな画面の問題について詳しくは触れませんでした。単にImageViewを使用して「png」イメージを表示しました。ユーザーがボタンをクリックすると、別の「png」イメージに変わります。
P.SこのプロジェクトはEclipse 3.7で開発され、Android 2.3.3.
でテストされています
1.画像をリソースに追加する
“res/drawable-ldpi`”、 “res/drawable-mdpi`”または “res/drawable-hdpi`”というフォルダにイメージを置きます。
下の図を参照してください。どのフォルダに置いても、Androidは自動的に画像を見つけます。この場合、デモには “android.png”と “android3d.png”の両方の画像が使用されます。
-
注** 再び、公式のAndroidの「http://developer.android.com/guide/topics/resources/drawable-resource.html[Drawable Resource]」と「http://developer.android.com/guide/practices」を読んでください。/screens__support.html[Screen Support]」の記事で、Androidのdpiとリソースについて理解しています。
2. ImageViewを追加する
”
res/layout/main.xml
“ファイルを開き、デモ用に
ImageView`と
Button`を追加してください。デフォルトで `imageView1`は” android.png “を表示します。
File:res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout__width="fill__parent"
android:layout__height="fill__parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout__width="wrap__content"
android:layout__height="wrap__content"
android:src="@drawable/android"/>
<Button
android:id="@+id/btnChangeImage"
android:layout__width="wrap__content"
android:layout__height="wrap__content"
android:text="Change Image"/>
</LinearLayout>
3.コードコード
シンプルなボタンをクリックすると、それを “android3d.png”に変更します。
ファイル:私のAndroid App Activity.java
package com.mkyong.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.view.View;
import android.view.View.OnClickListener;
public class MyAndroidAppActivity extends Activity {
Button button;
ImageView image;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
image = (ImageView) findViewById(R.id.imageView1);
button = (Button) findViewById(R.id.btnChangeImage);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
image.setImageResource(R.drawable.android3d);
}
});
}
}
4.デモ
アプリケーションを実行します。
{空} 1。結果、 “android.png”が表示されます。
{空} 2。ボタンをクリックすると、画像が “android3d.png”に変更されます。
ソースコードをダウンロードする
ダウンロードする –
Android-ImageView-Example.zip
(57 KB)
参考文献
ImageViewの例]。
http://developer.android.com/guide/topics/resources/drawable-resource.html
[Android
引き出し可能な資源]。
http://developer.android.com/guide/practices/screens__support.html
[Another
Androidスクリーンのサポート]
リンク://タグ/アンドロイド/[アンドロイド]リンク://タグ/画像/[画像]