自学android,书上有一个相簿的例子,代码写好后,运行不了,进入直接崩溃。我百度了类似的代码,感觉差不多。
因为是自学有一下问题:
1.在eclipse上,Gallery为什么被划掉了,
2.TypedArray a=obtainStyledAttributes(R.styleable.Gallery); mGalleryItemBackground=a.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0);
a.recycle();书上给的例子仅仅设定它有属性,那这个属性是什么,调用之后有什么用。
3.ImageAdapter中的各种方法,在程序中没有调用过,为什么要写。
4.怎么让这个程序能够正常运行。
非常感谢,看了好几天了,没看懂。
代码如下:
package com.example.xiangbo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Gallery g=(Gallery)findViewById(R.id.mygallery);
g.setAdapter(new ImageAdapter(this));
//ImageAdapter ia=new ImageAdapter(this);
g.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?>parent,View v,int position,long id){
Toast.makeText(MainActivity.this,getString(R.string.my_gallery_text_pre)+position+getString(R.string.my_gallery_text_post),Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
public class ImageAdapter extends BaseAdapter{
int mGalleryItemBackground;
private Context mContext;
public ImageAdapter(Context c){
super();
mContext=c;
TypedArray a=obtainStyledAttributes(R.styleable.Gallery);
mGalleryItemBackground=a.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount(){
return myImageIds.length;
}
public Object getItem(int position){
return position;
}
public long getItemId(int position){
return position;
}
public View getView(int position,View convertView,ViewGroup parent){
ImageView i=new ImageView(mContext);
i.setImageResource(myImageIds[position]);
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(136, 88));
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
private Integer[] myImageIds={
R.drawable.a1,
R.drawable.a2,
R.drawable.a3,
R.drawable.a4,
R.drawable.a5,
R.drawable.a6
};
}
@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;
}
}