Как собрать пользовательский ввод со многих слайдов ViewPager одним нажатием кнопки на последнем слайде? - PullRequest
0 голосов
/ 16 апреля 2020

Я стараюсь не перегружать пользователя, собирая много данных на одном экране, поэтому я использовал 'Viewpager' с 3 XML разметками. Моя кнопка находится на последнем слайде и я хочу сохранить все данные, которые я собрал в Firestore. У меня проблемы с получением информации со всех слайдов в одном упражнении. Каково решение моей проблемы.

Вот мой код onClickListener

           // Adding property details through onclick listener
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String location = Location.getText().toString().trim();
                        String surbab = Surbab.getText().toString().trim();
                        String city = City.getText().toString().trim();
                        String country = Country.getText().toString().trim();
                        String Name = name.getText().toString().trim();
                        Double Valuation = Double.valueOf(valuation.getText().toString().trim());
                        boolean Property_type = Boolean.parseBoolean(type.getText().toString().trim());
                        String No_of_units = number_of_units.getText().toString().trim();


                        String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

                        if (!validateInputs(location, surbab, city, country, Name, String.valueOf(Valuation), No_of_units)) {

                            CollectionReference dbTenants = db.collection("Users");


                            Property property = new Property(
                                    location,
                                    surbab,
                                    city,
                                    country,
                                    Name,
                                    Valuation,
                                    Property_type,
                                    No_of_units

                            );
                            dbTenants.document(uid).collection("property").add(property)
                                    .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                                        @Override
                                        public void onSuccess(DocumentReference documentReference) {
                                            Toast.makeText(PropertyActivity.this, "Tenant Added", Toast.LENGTH_SHORT).show();
                                        }
                                    }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(PropertyActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();

                                }
                            });
                        }
                    }
                });

Для класса свойств у меня есть это

package com.example.MyLandlordStudio;

public class Property {
    private String Locaation;
    private String Surbab;
    private String City;
    private String Country;
    private String name;
    private Double valuation;
    private boolean type;
    private String number_of_units;

    public Property() {

    }

    public Property(String locaation, String surbab, String city, String country, String name, Double valuation, boolean type, String number_of_units) {
        Locaation = locaation;
        Surbab = surbab;
        City = city;
        Country = country;
        this.name = name;
        this.valuation = valuation;
        this.type = type;
        this.number_of_units = number_of_units;
    }

    public String getLocaation() {
        return Locaation;
    }

    public String getSurbab() {
        return Surbab;
    }

    public String getCity() {
        return City;
    }

    public String getCountry() {
        return Country;
    }

    public String getName() {
        return name;
    }

    public Double getValuation() {
        return valuation;
    }

    public boolean isType() {
        return type;
    }

    public String getNumber_of_units() {
        return number_of_units;
    }
}

Вот визуальное представление того, что я среднее значение https://i.stack.imgur.com/8R8Gj.png. Когда я нажимаю зеленую кнопку, я хочу добавить все данные со всех слайдов в Firestore. Откройте ссылку для изображения. Заранее спасибо

Вот мой адаптер

import android.content.Context;
import android.os.Build;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

public class SliderAdapter extends PagerAdapter {

    Context context;
    LayoutInflater layoutInflater;

    public SliderAdapter(Context context) {
        this.context = context;
    }


    @Override
    public int getCount() {

        return 3;
    }


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

        LayoutInflater inflater = (LayoutInflater) container.getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        int resId = 0;
        switch (position) {
            case 0:
                resId = R.layout.address_slider_layout;
                break;
            case 1:
                resId = R.layout.description_slider_layout;
                break;
            case 2:
                resId = R.layout.confirm_slider_layout;
                break;

        }

        View view = inflater.inflate(resId, null);
        ((ViewPager) container).addView(view, 0);

        return view;

    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        ((ViewPager) container).removeView((View) object);
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == ((View) object);
    }

    @Nullable
    @Override
    public Parcelable saveState() {
        return null;
    }
}

@svi.data

1 Ответ

0 голосов
/ 18 апреля 2020

Вы можете добавить один метод в базовое действие / фрагмент, который содержит объект, содержащий эти значения.

, например, BaseFragment является родительским фрагментом viewpager

BaseFragment. java

//create object of property
Property property=new Property();

//this method can be accessed in all the viewpager
public Property getPropertyValues(){
   return property;
}

ViewPager1. java (первый просмотрщик)

//in onclick button or swipe add this
BaseFragment basefragment=(BaseFragment)ViewPager1.this.getParentFragment();
Property obj=basefragment.getPropertyValues();
obj.setLocation("your value");
...
...
 //same thing you have to do in viewpager2

viewpager3. java (последний просмотрщик)

BaseFragment basefragment=(BaseFragment)ViewPager1.this.getParentFragment();
Property obj=basefragment.getPropertyValues();
String location=obj.getLocation();
...
...
...
//here you will get all the values
...