在片段中使用AdapterViewFlipper来创建图像滑块

时间:2018-12-11 11:00:25

标签: android android-studio android-fragments slider viewflipper

我正在尝试在市场应用程序中创建图像滑块。我的应用程序在MainActivity中有3个片段,这些片段链接到BottomNavigationView。我尝试使用adapterViewFlipper在第一个片段中创建一个滑块。

这是第一个片段的布局:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="35dp"
    android:orientation="vertical">

    <AdapterViewFlipper
        android:id="@+id/adapterViewFlipper"
        android:layout_width="match_parent"
        android:layout_height="200dp">

    </AdapterViewFlipper>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recylcerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/item_margin"
        android:layout_marginTop="8dp"
        tools:layout_editor_absoluteX="745dp"
        tools:layout_editor_absoluteY="-51dp" />


</LinearLayout>

从服务器获取数据的方法:      私有无效FeaturedProductlistReq(String baseURL){

    OAuthInterceptor oauth1Woocommerce = new OAuthInterceptor.Builder()
            .consumerKey(getString(R.string.cunsomer_key))
            .consumerSecret(getString(R.string.consumersecret))
            .build();

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .addInterceptor(interceptor)
            .addInterceptor(oauth1Woocommerce)// Interceptor oauth1Woocommerce added
            .build();

    Retrofit mRetrofit = new Retrofit.Builder()
            .baseUrl(baseURL).addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    Api api = mRetrofit.create(Api.class);

    Call<List<Products>> call = api.getProducts(100);

    call.enqueue(new Callback<List<Products>>() {
        @Override
        public void onResponse(Call<List<Products>> call, Response<List<Products>> response) {
            try {

                for (int i = 0; i < response.body().size(); i++) {
                    Products array = response.body().get(i);

                    //adding the product to the product list
                    try {

                        if (array.isFeatured()) {
                            featuredProductlist.add(new FeaturedProduct(
                                    array.getName(),
                                    array.getImages().get(0).getSrc()

                            ));
                        }
                    } catch (Exception e) {
//                            Log.d("retrofit error", e.getMessage());

                    }
                }

                Log.d("featured getId", String.valueOf(featuredProductlist.get(0).getUrl()));
                Log.d("featured getId", String.valueOf(featuredProductlist.size()));


                featuredProductAdapter(featuredProductlist);

            } catch (Exception e) {
                Log.d("retrofit connection", String.valueOf(e.getMessage()));
                Toast.makeText(getContext(), "خطا در اتصال header", 
Toast.LENGTH_SHORT).show();


            }
        }

        @Override
        public void onFailure(Call<List<Products>> call, Throwable t) {
            Toast.makeText(getContext(), "خطا در اتصال", 
Toast.LENGTH_SHORT).show();

//                Toast.makeText(getContext(), t.getMessage(), 
Toast.LENGTH_SHORT).show();
//            Log.d("retrofit error", t.getMessage());
        }
    });


}

挡板适配器代码:

public class FlipperAdapter extends BaseAdapter {
private Context mCtx;
private ArrayList<FeaturedProduct> featuredProducts;

public FlipperAdapter(Context mCtx, ArrayList<FeaturedProduct> featuredProducts) {
    this.mCtx = mCtx;
    this.featuredProducts = featuredProducts;
}

@Override
public int getCount() {
    return featuredProducts.size();
}

@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) {

    FeaturedProduct featuredProduct = featuredProducts.get(position);

    LayoutInflater inflater = LayoutInflater.from(mCtx);
    View view = inflater.inflate(R.layout.flipper_items, null);
    TextView textView = view.findViewById(R.id.textViewflipper);
    ImageView imageView = view.findViewById(R.id.imageViewflipper);
    textView.setText(featuredProduct.getName());

    Glide.with(mCtx).load(featuredProduct.getUrl()).into(imageView);
    return view;
 }
}

和片段中的适配器方法:

      private void featuredProductAdapter(ArrayList<FeaturedProduct> featuredProductlist2) {

    Log.d("adapter error", "00000000000000");

    //creating adapter object
    FlipperAdapter adapter = new FlipperAdapter(getContext(), featuredProductlist2);
    Log.d("adapter error", adapter.getItem(0).toString());

    //adding it to adapterview flipper
    adapterViewFlipper.setAdapter(adapter);
    adapterViewFlipper.setFlipInterval(1000);
    adapterViewFlipper.startFlipping();
}

everthig可以,但是当它尝试在中创建适配器时:

           FlipperAdapter adapter = new FlipperAdapter(getContext(), featuredProductlist2);

它在logcat中返回此错误:

 D/retrofit connection: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

我用谷歌搜索,但是找不到解决我问题的好方法

有人知道是什么问题吗?还是可以给出在片段中创建图像滑块的解决方案?

预先感谢

1 个答案:

答案 0 :(得分:1)

那是因为您没有在适配器中正确实现getItem,所以在调用adapter.getItem(0).toString()时失败:

@Override
public Object getItem(int position) {
    // return null; you probably do not want to return null here
    return featuredProducts.get(position);
}