简单图片浏览器

此使用的知识点是XML布局文件与Java代码的混合来控制UI界面。
首先在布局文件中定义简单的线性布局容器:

<?xml version="1.0" encoding="utf-8"?>
<!--定义一个线性布局容器-->
<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.dell1.pictureview.MainActivity">
</LinearLayout>

此部分代码通俗易懂,注意该线性布局容器的id为root即可。
接下来我们在程序中获取该线性布局容器,并往该容器中添加组件。以下是java部分的运行代码:
首先我们定义一个访问图片的数组:(按照图片路径,图片应该保存在drawable之中)

int[] images = new int[] {
        R.drawable.pic1,
        R.drawable.pic2,
        ...
        R.drawable.picn, }
//初始化显示的图片
int currentImg = 0;

再获取LinearLayout布局容器

LinearLayout main = (LinearLayout) findViewById(R.id.root);

然后创建ImageView组件

final ImageView image = new ImageView(this);

再将ImageView组件添加到LinearLayout 布局容器中

main.addView(image);

接着在初始化时显示第一张图片

image.setImageResource(images[0]);

最后添加在屏幕受到点击时触发切换图片的事件,因此现在进行图片的切换:

image.setOnclickListener(new View.OnclickListener() {
    @override
    public void onClick(View v) {
    //change the current pic
    image.setImageResource(images[++currentImg % images.length])
    }
    });
}

最后,就可以点击手机屏幕进行切换了。
源代码:
https://github.com/WilliamYi96/Android/new/master/Training-Project/PictureView

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐