Как я могу достигнуть функциональности автоигры с переработчиком? - PullRequest
0 голосов
/ 20 января 2020

Я бы хотел использовать пейджинговый адаптер с утилитой панелью для просмотра автоматического слайда, как показано на рисунке ниже. Как мне этого добиться? :

image of the layout I would like to achieve

Редактировать

Моя основная деятельность:

public class MainActivity extends AppCompatActivity implements 
    NavigationView.OnNavigationItemSelectedListener {

    private ActionBarDrawerToggle toggle;
    private DrawerLayout drawerLayout;

    private Toolbar toolbar;

    private int[] images = {
            R.drawable.image1, R.drawable.image2,
            R.drawable.image3, R.drawable.image4,
            R.drawable.image5
    };

    private String[] trendingNames = {
            "Sneaker 1", "Sneaker 2",
            "Sneaker 3", "Sneaker 4",
            "Sneaker 5"
    };

    private String[] trendingPrices = {
            "$100", "$100",
            "$100", "$100",
            "$100"
    };

    private int[] store_images = {
            R.drawable.queen1, R.drawable.pice1,
            R.drawable.store3, R.drawable.store4,
            R.drawable.store5
    };

    private String[] store_names = {
            "Queenda5 Mother Care", "Pice Restaurant",
            "Kingdom Books & Stationary", "Central Shoe Shop",
            "Apple World GH"
    };

    private String[] store_locations = {
            "Kumasi - Adum", "Kumasi City Mall",
            "Kumasi - KNUST", "Kumasi - Adum",
            "Kumasi - Adum"
    };

    private final RecyclerView.LayoutManager trending_layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

    private RecyclerView stores_recyclerview;
    private RecyclerView.LayoutManager stores_layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        final int time = 2000;


        toolbar = findViewById(R.id.main_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);

        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);


        final RecyclerView trending_recyclerView = findViewById(R.id.trending_recyclerview);
        trending_recyclerView.setLayoutManager(trending_layoutManager);
        //trending_recyclerView.setHasFixedSize(true);

        final LinearSnapHelper linearSnapHelperClass = new LinearSnapHelper();
        linearSnapHelperClass.attachToRecyclerView(trending_recyclerView);

        final TrendingAdapter adapter = new TrendingAdapter(this, trendingNames, trendingPrices, images);
        trending_recyclerView.setAdapter(adapter);

        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {

                if (linearLayoutManager.findLastCompletelyVisibleItemPosition() < (adapter.getItemCount() - 1)) {

                    linearLayoutManager.smoothScrollToPosition(trending_recyclerView, new RecyclerView.State(), linearLayoutManager.findLastCompletelyVisibleItemPosition() + 1);
                }

                else if (linearLayoutManager.findLastCompletelyVisibleItemPosition() == (adapter.getItemCount() - 1)) {

                    linearLayoutManager.smoothScrollToPosition(trending_recyclerView, new RecyclerView.State(), 0);
                }
            }
        }, 0, time);

        stores_recyclerview = findViewById(R.id.stores_recyclerview);
        stores_layoutManager = new LinearLayoutManager(this);
        stores_recyclerview.setLayoutManager(stores_layoutManager);
        stores_recyclerview.setHasFixedSize(true);

        StoresAdapter adapter1 = new StoresAdapter(this, store_images, store_names, store_locations);
        stores_recyclerview.setAdapter(adapter1);

        drawerLayout = findViewById(R.id.main_drawer_layout);
        toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        if (toggle.onOptionsItemSelected(item)) {
            return true;
        }

        switch (item.getItemId()) {

            case R.id.main_cart_id:
                Intent cartIntent = new Intent(MainActivity.this, CartActivity.class);
                cartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(cartIntent);
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //inflating menu items onto the toolbar

        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main_menu, menu);

        return true;
    }


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

        return true;
    }
}

Мой адаптер :

public class TrendingAdapter extends RecyclerView.Adapter<TrendingAdapter.TrendingViewHolder> {

    private Context context;
    private String[] trendingNames;
    private String[] trendingPrices;
    private int[] trendingImages;

    private List<String> cartImages;
    private List<String> cartNames;
    private List<String> cartPrices;

    public TrendingAdapter(Context context, String[] trendingNames, String[] trendingPrices, int[] trendingImages) {
        this.context = context;
        this.trendingNames = trendingNames;
        this.trendingPrices = trendingPrices;
        this.trendingImages = trendingImages;
    }

    @NonNull
    @Override
    public TrendingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.trending_item_layout, parent, false);
        return new TrendingViewHolder(view,context);
    }

    @Override
    public void onBindViewHolder(@NonNull final TrendingViewHolder holder, int position) {

        holder.item_image.setImageResource(trendingImages[position]);
        holder.item_name.setText(trendingNames[position]);
        holder.item_price.setText(trendingPrices[position]);

        cartImages = new ArrayList<>();
        cartNames = new ArrayList<>();
        cartPrices = new ArrayList<>();

        final int image = trendingImages[position];
        final String name = trendingNames[position];
        final String price = trendingPrices[position];

        holder.add_to_cart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                cartImages = PreferencesUtils.getCartImages(context);
                cartNames = PreferencesUtils.getCartNames(context);
                cartPrices = PreferencesUtils.getCartPrices(context);

                cartImages.add(String.valueOf(image));
                cartNames.add(name);
                cartPrices.add(price);

                PreferencesUtils.saveCartList(cartImages, cartNames, cartPrices, context);
            }
        });

    }

    @Override
    public int getItemCount() {
        return trendingNames.length;
    }


    public static class TrendingViewHolder extends RecyclerView.ViewHolder{

        private ImageView item_image;
        private TextView item_name, item_price;
        private Button add_to_cart;

        public TrendingViewHolder(@NonNull final View itemView, final Context context) {
            super(itemView);

            item_image = itemView.findViewById(R.id.trending_item_image);
            item_name = itemView.findViewById(R.id.trending_item_name);
            item_price = itemView.findViewById(R.id.trending_item_price);
            add_to_cart = itemView.findViewById(R.id.trending_add_to_cart);


            itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (hasFocus){

                        Animation anim = AnimationUtils.loadAnimation(context, R.anim.scale_in);
                        itemView.startAnimation(anim);
                        anim.setFillAfter(true);
                    }
                    else{
                        // run scale animation and make it smaller
                        Animation anim = AnimationUtils.loadAnimation(context, R.anim.scale_out);
                        itemView.startAnimation(anim);
                        anim.setFillAfter(true);
                    }
                }
            });
        }
    }

}

Я сделал все, что предлагалось, но приложение по-прежнему зависает.

1 Ответ

2 голосов
/ 20 января 2020

попробуйте с этим, это может помочь вам

  RecyclerView recyclerView = findViewById(R.id.recyclerview);

    final int time = 2000; // it's the delay time for sliding between items in recyclerview

    final AdapterClass adapter = new AdapterClass(list,context);

    final CenterZoomLayoutManager linearLayoutManager = new CenterZoomLayoutManager(context, CenterZoomLayoutManager.HORIZONTAL, false);
    recyclerView.setLayoutManager(linearLayoutManager);

// если размер списка больше нуля, используйте его для автоматического масштабирования первого элемента

       linearLayoutManager.setTargetStartPos(1,1);
      recyclerView.setAdapter(adapter);

// LinearSnapHelper привязывает центр целевого дочернего представления к центру присоединенного RecyclerView, это необязательно, если вы хотите, вы можете использовать его

        final LinearSnapHelper linearSnapHelperClass = new LinearSnapHelper();
    linearSnapHelperClass.attachToRecyclerView(recyclerView);

    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {

            if  (linearLayoutManager.findLastCompletelyVisibleItemPosition() < (adapter.getItemCount() - 1)) {

                linearLayoutManager.smoothScrollToPosition(recyclerView, new RecyclerView.State(), linearLayoutManager.findLastCompletelyVisibleItemPosition() + 1);
            }

            else if (linearLayoutManager.findLastCompletelyVisibleItemPosition() == (adapter.getItemCount() - 1)) {

                linearLayoutManager.smoothScrollToPosition(recyclerView, new RecyclerView.State(), 0);
            }
        }
    }, 0, time);

Используйте этот класс для масштабирования изображения по центру.

 package com.example.android.androidtask.model;

import android.content.Context;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class CenterZoomLayoutManager extends LinearLayoutManager {

private final float mShrinkAmount = 0.15f;
private final float mShrinkDistance = 0.9f;
private int mPendingTargetPos = -1;
private int mPendingPosOffset = -1;

public CenterZoomLayoutManager(Context context) {
    super(context);
}

public CenterZoomLayoutManager(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
}


@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
    int orientation = getOrientation();
    if (orientation == VERTICAL) {
        int scrolled = super.scrollVerticallyBy(dy, recycler, state);
        float midpoint = getHeight() / 2.f;
        float d0 = 0.f;
        float d1 = mShrinkDistance * midpoint;
        float s0 = 1.f;
        float s1 = 1.f - mShrinkAmount;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            float childMidpoint =
                    (getDecoratedBottom(child) + getDecoratedTop(child)) / 2.f;
            float d = Math.min(d1, Math.abs(midpoint - childMidpoint));
            float scale = s0 + (s1 - s0) * (d - d0) / (d1 - d0);
            child.setScaleX(scale);
            child.setScaleY(scale);
        }
        return scrolled;
    } else {
        return 0;
    }
}

@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
    int orientation = getOrientation();
    if (orientation == HORIZONTAL) {
        int scrolled = super.scrollHorizontallyBy(dx, recycler, state);

        float midpoint = getWidth() / 2.f;
        float d0 = 0.f;
        float d1 = mShrinkDistance * midpoint;
        float s0 = 1.f;
        float s1 = 1.f - mShrinkAmount;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            float childMidpoint =
                    (getDecoratedRight(child) + getDecoratedLeft(child)) / 2.f;
            float d = Math.min(d1, Math.abs(midpoint - childMidpoint));
            float scale = s0 + (s1 - s0) * (d - d0) / (d1 - d0);
            child.setScaleX(scale);
            child.setScaleY(scale);
        }
        return scrolled;
    } else {
        return 0;
    }

}


@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
    if (mPendingTargetPos != -1 && state.getItemCount() > 0) {
        /*
        Data is present now, we can set the real scroll position
        */
        scrollToPositionWithOffset(mPendingTargetPos, mPendingPosOffset);
        mPendingTargetPos = -1;
        mPendingPosOffset = -1;
    }
    super.onLayoutChildren(recycler, state);
}

@Override
public void onRestoreInstanceState(Parcelable state) {
    /*
    May be needed depending on your implementation.

    Ignore target start position if InstanceState is available (page existed before already, keep position that user scrolled to)
     */
    mPendingTargetPos = -1;
    mPendingPosOffset = -1;
    super.onRestoreInstanceState(state);
}

/**
 * Sets a start position that will be used <b>as soon as data is available</b>.
 * May be used if your Adapter starts with itemCount=0 (async data loading) but you need to
 * set the start position already at this time. As soon as itemCount > 0,
 * it will set the scrollPosition, so that given itemPosition is visible.
 * @param position
 * @param offset
 */
public void setTargetStartPos(int position, int offset) {
    mPendingTargetPos = position;
    mPendingPosOffset = offset;
}

}

...