安卓入门小程序
1.mainactivity
package com.example.pro.first; import android.support.v7.app.AppCompatActivity; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.LinearLayout; public class Main2Activity extends Activity { int[] images = new int[]{ R.drawable.a1, R.drawable.a2, //res/drawable文件夹下面图片的名字 教程上应该是下面的代码 但是报错 /* R.drawable.swift, R.drawable.ajax, R.drawable.html, */ }; int currentImg = 0 ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); LinearLayout main = (LinearLayout) findViewById(R.id.linerlayout); final ImageView image = new ImageView(this); main.addView(image); image.setImageResource(images[0]); image.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { image.setImageResource(images[++currentImg % images.length]); } }); } }
2.activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main2" 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.pro.first.Main2Activity"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:id="@+id/linerlayout"></LinearLayout> </RelativeLayout>
运行界面如下 图片是自己放在 res/drawable文件夹下面的图片