xml文件
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/mygallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:scaleType="fitCenter"
android:contentDescription="@string/desc" />
mainActivity
public class MainActivity extends Activity implements View.OnClickListener
{
private LinearLayout myGallery;
private ImageView showImage;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myGallery = (LinearLayout)findViewById(R.id.mygallery);
showImage = (ImageView)findViewById(R.id.imageView);
Integer[] images = {R.drawable.item1, R.drawable.item2, R.drawable.item3, R.drawable.item4, R.drawable.item5};
for(Integer id:images)
{
myGallery.addView(insertImage(id));
}
}
@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;
}
private View insertImage(Integer id)
{
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setLayoutParams(new LayoutParams(320, 320));
layout.setGravity(Gravity.CENTER);
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new LayoutParams(300, 300));
imageView.setBackgroundResource(id);
imageView.setOnClickListener(this);
imageView.setId(id);
layout.addView(imageView);
return layout;
}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
ImageView imageView = (ImageView)v;
showImage.setImageResource(imageView.getId());
}
}