【Android开发学习】简单的图片浏览

基于Android 4.2 SDK

布局文件如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

</RelativeLayout>

Java源代码如下:

package com.example.image_display_demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {
	int[] images = new int[]{
			R.drawable.dff1,
			R.drawable.dff2,
			R.drawable.dff3,
			R.drawable.dff4,
			R.drawable.dff5,
			R.drawable.dff6,
	};
	int currentImage = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//获取RelativeLayout布局容器
		RelativeLayout layout = (RelativeLayout)findViewById(R.id.root);
		
		//程序创建ImageView组件
		final ImageView image = new ImageView(this);
		
		//将ImageView组件添加到RelativeLayout布局容器中
		layout.addView(image);
		
		//初始化时显示第一张图片
		image.setImageResource(images[0]);
		image.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				image.setImageResource(images[++currentImage % images.length]);
			}
		});
	}

	@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;
	}

}


你可能感兴趣的:(【Android开发学习】简单的图片浏览)