Android Studio setAdapter无法识别

时间:2015-06-23 01:11:09

标签: android android-studio

我在Android Boot Camp for Developers第2版的第7章中进行了练习。本书针对ICS,但我试图不使用已弃用的图库小部件,而是使用 Horizo​​ntalScrollView

现在 setAdapter 尚未被识别,在代码中我还有一个问题, arg0 arg2 也未被识别。我可以通过将对 Horizo​​ntalScrollView 的调用还原为图库来解决 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;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

将这两个变量替换为position

答案 1 :(得分:0)

您需要使用LinearLayout包含HorizontalScrollView或类似内容,与使用常规ScrollView完全相同。其他(更好)选项是使用RecyclerViewLinearLayoutManager,将其调整为水平滚动。像这样:

mRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));

在这种情况下,您需要使适配器扩展RecyclerView.Adapter