1,需求样式
2,建立viewer.xml文件,选择LinearLayout布局
使用ImageView控件和Buttons控件
如图:
代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical"> 7 8 <ImageView 9 android:id="@+id/img" 10 android:layout_width="match_parent" 11 android:layout_height="522dp" 12 android:scaleType="centerInside" 13 app:srcCompat="@mipmap/a" /> 14 15 <LinearLayout 16 android:layout_width="match_parent" 17 android:layout_height="55dp" 18 android:orientation="horizontal"> 19 20 <Button 21 android:id="@+id/last" 22 android:layout_width="0dp" 23 android:layout_height="wrap_content" 24 android:layout_weight="1" 25 android:text="上一张" /> 26 27 <Button 28 android:id="@+id/next" 29 android:layout_width="0dp" 30 android:layout_height="wrap_content" 31 android:layout_weight="1" 32 android:text="下一张" /> 33 </LinearLayout> 34 </LinearLayout>
注:在使用button控件时我们需要两个,分别是“上一张”和“下一张”,这里把两个组件放到一个横向布局里(第15行)
这里需要在button控件里使用weight,这个管理的是横向布局里的两个button的宽度占比,对应到垂直布局则控制高度占比
android:layout_weight="1"
我们需要把两个button的宽度改为0dp,然后设置weight值都为1,意思为各占一半
如果一个设置为1,另一个设置为3,则第一个宽度占比为1,第二个宽度占比为3.
对应到垂直布局道理类似
3,新建ViewerActivity.java
代码如下:
1 package com.example.myapplication; 2 import android.os.Bundle; 3 import android.view.View; 4 import android.widget.Button; 5 import android.widget.ImageView; 6 7 import androidx.appcompat.app.AppCompatActivity; 8 9 public class ViewerActivity extends AppCompatActivity implements View.OnClickListener{ 10 private Button last; 11 private Button next; 12 private ImageView img; 13 private int[] p = {R.mipmap.a,R.mipmap.b,R.mipmap.c};//图片组 R.图片目录.图片名 14 private int Index = 0; //图片的当前索引位置 15 private int count = p.length-1; 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState);//创造 19 setContentView(R.layout.viewer);///设置内容视图 20 init();//初始化 21 } 22 //初始化 23 private void init() { 24 last = (Button) findViewById(R.id.last);//按ID查找控件 25 last.setOnClickListener(this);//单击设置监听器 26 next = (Button)findViewById(R.id.next); 27 next.setOnClickListener(this); 28 img =(ImageView) findViewById(R.id.img); 29 } 30 //单击事件 31 public void onClick(View view) { 32 //view.getID获取ID,判断是哪一个 33 switch (view.getId()) { 34 case R.id.last: 35 //如果当前图片是第一张,则上一张图片为最后一张图片 36 if (Index == 0) { 37 Index = count; 38 } else { 39 //否则改为上一张图片 40 Index = Index - 1; 41 } 42 break; 43 case R.id.next: 44 //如果当前图片是最后一张,则下一张图片为第一张图片 45 if (Index == count) { 46 Index = 0; 47 } else { 48 //否则改为下一张图片 49 Index = Index + 1; 50 } 51 break; 52 default: 53 break; 54 } 55 img.setImageResource(p[Index]); //显示图片 56 } 57 }
其中第14行定义了一个图片组,mipmap为图片所在目录,其后的a,b,c为图片的名称
private int[] p = {R.mipmap.a,R.mipmap.b,R.mipmap.c};//图片组 R.图片目录.图片名
放图片的目录mipmap可以换,图片名是根据自己的图片名设置的
如果你的图片名为d.png,则相应代码要改为R.mipmap.d
规则:R.图片目录.图片名
其中图片的名字不可包含空格
4,效果图如下: