我正在为开发者做第二版的安卓启动营的ch7练习。这本书的目标是ICS,但我尝试不使用被废弃的图片库小部件,而是使用。
现在,setAdapter没有被识别,在代码中,我也遇到了arg0和arg2也没有被识别的问题。我可以通过将对HorizontalScrollView的调用恢复到来解决setAdapter问题,但是arg问题仍然存在。下面是这个小类文件的全部代码。
谢谢!
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
public Integer[] Animals = {R.drawable.elephant, R.drawable.gorilla, R.drawable.leopard, R.drawable.monkey, R.drawable.panda, R.drawable.redpanda};
ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HorizontalScrollView ga = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);
imageView = (ImageView) findViewById(R.id.imgAnimal);
ga.setAdapter(new ImageAdapter(this));
ga.setOnClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), "You have selected picture " + (arg2 + 1)
+ " of the endangered species", Toast.LENGTH_SHORT).show();
imageView.setImageResource(Animals[arg2]);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context c) {
context = c;
}
@Override
public int getCount() {
return Animals.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView pic = new ImageView(context);
pic.setImageResource(Animals[arg0]);
pic.setScaleType(ImageView.ScaleType.FIT_XY);
pic.setLayoutParams(new HorizontalScrollView.LayoutParams(200, 175));
return pic;
}
}
}发布于 2015-06-23 01:45:21
将这两个变量替换为position
发布于 2015-06-23 01:54:37
您需要将LinearLayout或类似的东西包装在HorizontalScrollView中,就像使用常规ScrollView那样。其他(更好的)选项是使用RecyclerView和LinearLayoutManager,调整它以水平滚动。就像这样:
mRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));在这种情况下,需要使适配器扩展RecyclerView.Adapter。
https://stackoverflow.com/questions/30992306
复制相似问题