ViewPager, использующий представления вместо фрагментов

У меня есть ViewPager, который теперь использует Views вместо Fragments для отображения каждой вкладки. Каждая отдельная вкладка раздувает один и тот же файл макета.


Обзор

В этом ViewPager я должен добавить шахты в виде вкладок, поэтому в основном каждая вкладка будет соответствовать определенной шахте (те, что с минералами, а не бомбой).

Некоторые шахты уже разблокированы, но некоторые другие нужно сначала купить, поэтому я добавил button, чтобы сделать именно это.

Проблема

Дело в том, что с использованием фрагментов все работало нормально, но теперь я поменял их местами с просмотрами, я могу купить шахту, но потом, если я куплю другой, тот, который я ранее купил, блокируется обратно, поскольку я никогда его не покупал.


КОД

Сейчас я действительно запутался, я не знаю, в чем проблема, но я могу дать вам наиболее важные части кода:

МайнерАдаптер

public class MineAdapter extends PagerAdapter {
private Context mContext;
private LayoutInflater mLayoutInflater;

public MineAdapter(Context context) {
    mContext = context;
    mLayoutInflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public Object instantiateItem(ViewGroup container, final int position) {

    System.out.println("Code executed");

    final View itemView = mLayoutInflater.inflate(R.layout.carousal_page, container,
            false);

    switch (position) {
        case 0:
            itemView.setBackgroundResource(R.color.iron);
            break;
        case 1:
            itemView.setBackgroundResource(R.color.coal);
            break;
        case 2:
            itemView.setBackgroundResource(R.color.gold);
            break;
    }

    [Some setup skipped]

    // Unlock Button
    itemView.findViewById(R.id.unlockButton).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (CenterRepository.getSingletonInstance().getCurrentUser().getGold() >=
                    CenterRepository.getSingletonInstance().getListOfLavels().get(position).getUnlockCost()) {

                //If User has more gold than cost to unlock remove lock image and buy it

                CenterRepository.getSingletonInstance().getCurrentUser().setGold(
                        CenterRepository.getSingletonInstance().getCurrentUser().getGold()
                                - CenterRepository.getSingletonInstance().getListOfLavels().get(position).getUnlockCost()); // Update user's gold


                itemView.findViewById(R.id.unlockButton).setVisibility(View.GONE); // Remove lock button


                Toast.makeText(mContext,
                        "Reduced " + CenterRepository.getSingletonInstance().getListOfLavels().get(position).getUnlockCost() +
                                "\n Updated Gold " + CenterRepository.getSingletonInstance()
                                .getCurrentUser().getGold(), Toast.LENGTH_LONG).show();

            } else {

                // Not enough money
                Toast.makeText(mContext, "Not enough money to purchase You need " +
                        (CenterRepository.getSingletonInstance().getListOfLavels().get(position).getUnlockCost()
                                - CenterRepository.getSingletonInstance().getCurrentUser().getGold()) + "More", Toast.LENGTH_SHORT).show();
            }

        }
    });

    container.addView(itemView);

    return itemView;
    }
}

XML-макет

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/mineName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:text="COAL MINE"
        android:textColor="@android:color/white"
        android:textSize="25sp" />


    <TextView
        android:id="@+id/mineCost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="5"
        android:gravity="center"
        android:text="1000"
        android:textColor="@android:color/white"
        android:textSize="50sp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:paddingEnd="100dp"
        android:paddingStart="100dp">

        <TextView
            android:id="@+id/mineMineral"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignTop="@+id/mineDropRate"
            android:text="COAL"
            android:textAlignment="center"
            android:textColor="@android:color/white"
            android:textSize="25sp" />

        <TextView
            android:id="@+id/mineDropRate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerVertical="true"
            android:text="1"
            android:textAlignment="center"
            android:textColor="@android:color/white"
            android:textSize="25sp" />

    </RelativeLayout>
</LinearLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/unlockButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Unlock" />

</RelativeLayout>


Основная деятельность

public class MainActivity extends AppCompatActivity {

ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //  Add Test User from Activity
    CenterRepository.getSingletonInstance().setCurrentUser(new User("FET", 2000, 20, 10));

    //Add Test Mines
    CenterRepository.getSingletonInstance().getListOfLavels().clear();
    CenterRepository.getSingletonInstance().addMine(new Mine("Iron", new Mineral("Iron Mineral", 1), 100, 2));
    CenterRepository.getSingletonInstance().addMine(new Mine("Coal", new Mineral("Coal Mineral", 3), 200, 2));
    CenterRepository.getSingletonInstance().addMine(new Mine("Gold", new Mineral("Gold Mineral", 2), 300, 2));

    viewPager = (ViewPager) findViewById(R.id.vpPager);
    viewPager.setAdapter(new MineAdapter(this));
    }
}

Дополнительный

If you prefer working with GitHub, here's the project with the full code with no skipped code.


person FET    schedule 23.09.2016    source источник