android ImageView实现图片浏览器(点击左侧显示上一张,点击右侧显示下一张)[通俗易懂]

android ImageView实现图片浏览器(点击左侧显示上一张,点击右侧显示下一张)[通俗易懂]1.实现代码如下:publicclassMainActivityextendsActivity{ privateint[]mImages={R.drawable.juxie,R.drawable.mojie, R.drawable.sheshou,R.drawable.shizi,R.drawable.shuangyu, R.drawable.shua

大家好,欢迎来到IT知识分享网。

1.实现代码如下:

public class MainActivity extends Activity {

	private int[] mImages = { R.drawable.juxie, R.drawable.mojie,
			R.drawable.sheshou, R.drawable.shizi, R.drawable.shuangyu,
			R.drawable.shuangzi, R.drawable.shuiping, R.drawable.tiancheng,
			R.drawable.tianxie };
	private String[] mImageNames = { "巨蟹座", "摩羯座", "射手座", "狮子座", "双鱼座", "双子座",
			"水平座", "天秤座", "天蝎座" };

	private int mCurrentImage = 0;

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

		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		final int width = metric.widthPixels;

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

		final EditText edit = (EditText) findViewById(R.id.edt);

		imgView.setImageResource(mImages[0]);

		edit.setText(mImageNames[0]);

		imgView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					if (event.getX() < width / 2) {
						if (mCurrentImage == 0) {
							mCurrentImage = mImages.length - 1;
						} else {
							mCurrentImage--;
						}
					} else {
						if (mCurrentImage == mImages.length - 1) {
							mCurrentImage = 0;
						} else {
							mCurrentImage++;
						}
					}
				}

				imgView.setImageResource(mImages[mCurrentImage]);
				edit.setText(mImageNames[mCurrentImage]);
				return true;
			}
		});

	}
}

2.实现效果

android ImageView实现图片浏览器(点击左侧显示上一张,点击右侧显示下一张)[通俗易懂]

3.该程序用到了获取屏幕大小的方法:

DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		final int width = metric.widthPixels;

为什么要获取pixel而不是dip呢,这是因为我查看了API后得出的结果,在onTouch()方法中通过event.getX();返回的正是pix。API中是这样说的:

getX
public final float getX()Returns the X coordinate of this event. <span style="color:#ff0000;">Whole numbers are pixels;</span> the value may have a fraction for input devices that are sub-pixel precise. 

4.给出px和dip的转换:

public static int dip2px(Context context, float dipValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}


public static int px2dip(Context context, float pxValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}

希望以后可以用上这个转换

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/25517.html

(0)

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信