学习第一个Android程序
今天学习写第一个android程序,是一个点击屏幕可以进行图片循环的,用XML进行布局,并用JAVA生成ImageView组件。
XML文件源码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
定义了一个线性布局,并设置名字为root.
在Activity中的源码如下:
package com.example.testimageview;
//对使用的要进行声明
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.LinearLayout;
import android.widget.ImageView;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
//定义一个数组,调用图片
int[] images=new int[]{
//以下为图片的资源文件,java,classic,ajax,ee,xml为图片文件名。通过导入到res目录下。
R.drawable.java,
R.drawable.classic,
R.drawable.ajax,
R.drawable.ee,
R.drawable.xml,
};
//定义一个标记,进行图片循环
int currentImg=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//用setContentView来显示视图
setContentView(R.layout.activity_main);
//获取LinearLayout布局容器妈
LinearLayout activity_main=(LinearLayout)findViewById(R.id.root);
//用代码创建ImageView 组件I
final ImageView image=new ImageView(this);
//将ImageView组件添加到LinearLayout布局容器中
activity_main.addView(image);
//初始化时显示第一张图片
image.setImageResource(images[0]);
image.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if (currentImg >=4)
{
currentImg=-1;
}
image.setImageResource(images[++currentImg]);
}
});
}
@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;
}
}
图片资源文件导入到res文件夹下。
浙公网安备 33010602011771号