程式運作結果截圖:
運作程式截圖
MainActivity.java代碼如下:
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity
{
private ImageView imgv;
LinearLayout h1;
int [] imgs=
{
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5,
R.drawable.img6,
R.drawable.img7,
R.drawable.img8
};
ImageView vs[];
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
h1=(LinearLayout)findViewById(R.id.h1);
imgv=(ImageView)findViewById(R.id.imgv);
imgv.setImageResource(R.drawable.img1);
vs=new ImageView[]
{
new ImageView(this),
new ImageView(this),
new ImageView(this),
new ImageView(this),
new ImageView(this),
new ImageView(this),
new ImageView(this),
new ImageView(this)
};
for(int i=0;i< vs.length;i++)
{
vs[i].setImageResource(imgs[i]);
vs[i].setLayoutParams(new LayoutParams(120,120));
vs[i].setOnClickListener(new hkf());
h1.addView(vs[i]);
}
}
class hkf implements OnClickListener
{
public void onClick(View v)
{
int i;
for(i=0;i< vs.length;i++)
{
if(v==vs[i])break;
}
imgv.setImageResource(imgs[i]);
}
}
}
activity_main.xml代碼如下:
< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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.hkf4.MainActivity" >
< ImageView
android:id="@+id/imgv"
android:layout_width="400dp"
android:layout_height="400dp" />
< HorizontalScrollView
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
< LinearLayout
android:id="@+id/h1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
</ LinearLayout>
</ HorizontalScrollView>
</ RelativeLayout>