android-数据在viewPage中丢失

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android-数据在viewPage中丢失相关的知识,希望对你有一定的参考价值。

在我的应用中,我使用“查看”页面进行了注册。当我滑动下一个或上一个数据时,还是在那里,但是当我在最后一页(第三页)中时,下一个按钮变为完成按钮,当我按完成并尝试读取值时,所有内容都为空。

我读到一种解决方案是添加-

viewPager = (ViewPager) findViewById(R.id.view_pager); 
viewPager.setOffscreenPageLimit(3);

所以我做到了,但没有解决问题。我也读过那些用片段做的人,而不是-

getactivity().getSupportFragmentmanager()

已用-

getChildFragmentManager()

这为他们解决了问题,但我没有使用片段。

我的Java代码:(我删除了不相关的代码以使其更短)。

package com.technion.cue.BusinessFeatures;

import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import java.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.text.html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import java.text.ParseException;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import com.technion.cue.R;
import com.technion.cue.SignInActivity;
import com.technion.cue.annotations.ModuleAuthor;
import com.technion.cue.data_classes.Business;
import androidx.appcompat.widget.AppCompatEditText;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static com.technion.cue.FirebaseCollections.BUSINESSES_COLLECTION;

@ModuleAuthor("Topaz")
public class BusinessSignUp2 extends AppCompatActivity {

    private ViewPager viewPager;
    private MyViewPagerAdapter myViewPagerAdapter;
    private LinearLayout dotsLayout;
    private TextView[] dots;
    private int[] layouts;
    private Button btnPrev, btnNext;
    private PrefManager prefManager;
    private static final int GET_LOGO = 0;

    FirebaseAuth mAuth;
    FirebaseFirestore db;

    Uri logoData;
    Map<String, String> open_hours = new HashMap<>();
    String lastUsedKey;
    View bo_signup1;
    View bo_signup2;
    View bo_signup3;


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

        final LayoutInflater factory = getLayoutInflater();
        bo_signup1 = factory.inflate(R.layout.activity_bo_sign_up, null);
        bo_signup2 = factory.inflate(R.layout.activity_bo_sign_up2, null);
        bo_signup3 = factory.inflate(R.layout.activity_bo_sign_up3, null);

        mAuth = FirebaseAuth.getInstance();
        db = FirebaseFirestore.getInstance();

        viewPager = (ViewPager) findViewById(R.id.view_pager);
        viewPager.setOffscreenPageLimit(3);
        dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
        btnPrev = (Button) findViewById(R.id.btn_prev);
        btnNext = (Button) findViewById(R.id.btn_next);


        layouts = new int[]{
                R.layout.activity_bo_sign_up,
                R.layout.activity_bo_sign_up2,
                R.layout.activity_bo_sign_up3};

        // adding bottom dots
        addBottomDots(0);

        // making notification bar transparent
        changeStatusBarColor();

        myViewPagerAdapter = new MyViewPagerAdapter();
        viewPager.setAdapter(myViewPagerAdapter);
        viewPager.addOnPageChangeListener(viewPagerPageChangeListener);

        btnPrev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //check if first page
                int current = getItem(-1);
                if (current >= 0) {
                    viewPager.setCurrentItem(current);
                } else {
                    //Todo: what else?
                }
            }
        });

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checking for last page
                int current = getItem(+1);
                if (current < layouts.length) {
                    // move to next screen
                    viewPager.setCurrentItem(current);
                } else {
                    //last page - done was clicked
                    Toast.makeText(BusinessSignUp2.this,
                            "done was clicked", Toast.LENGTH_LONG).show();

                    TextInputEditText email = bo_signup1.findViewById(R.id.businessEmailEditText);
                    TextInputEditText password = (bo_signup1.findViewById(R.id.businessPasswordEditText));
                    TextInputEditText boFullName = (bo_signup1.findViewById(R.id.businessFullNameEditText));
                    TextInputEditText businessName = (bo_signup2.findViewById(R.id.businessNameEditText));
                    TextInputEditText businessDescription = (bo_signup2.findViewById(R.id.businessDescriptionEditText));
                    TextInputEditText phone = (bo_signup2.findViewById(R.id.businessPhoneEditText));
                    TextInputEditText state = (bo_signup3.findViewById(R.id.businessStateEditText));
                    TextInputEditText city = (bo_signup3.findViewById(R.id.businessCityEditText));
                    TextInputEditText address = (bo_signup3.findViewById(R.id.businessAddressEditText));
                    TextView openHours = (bo_signup3.findViewById(R.id.openingHoursEditText));
                    TextView closeHours = bo_signup3.findViewById(R.id.closingHoursEditText);
                    boolean res = check_if_input_valid();

                    if (res) {
                        mAuth.createUserWithEmailAndPassword(email.getText().toString(), password.getText().toString()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                            @Override
                            public void onSuccess(AuthResult authResult) {
                                FirebaseUser user = mAuth.getCurrentUser();
                                Business business = new Business(businessName.getText().toString(),
                                        boFullName.getText().toString(), phone.getText().toString(),
                                        businessDescription.getText().toString());
                                db.collection(BUSINESSES_COLLECTION)
                                        .document(user.getUid())
                                        .set(business);
                                finish();
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                // If sign in fails, display a message to the user.
                                Toast.makeText(BusinessSignUp2.this,
                                        "failed", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                    else{
                        Toast.makeText(BusinessSignUp2.this,
                                "Please check the fields!", Toast.LENGTH_LONG).show();
                    }
                }
            }});
    }

    private void addBottomDots(int currentPage) {
        dots = new TextView[layouts.length];

        int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
        int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);

        dotsLayout.removeAllViews();
        for (int i = 0; i < dots.length; i++) {
            dots[i] = new TextView(this);
            dots[i].setText(Html.fromHtml("&#8226;"));
            dots[i].setTextSize(35);
            dots[i].setTextColor(colorsInactive[currentPage]);
            dotsLayout.addView(dots[i]);
        }

        if (dots.length > 0)
            dots[currentPage].setTextColor(colorsActive[currentPage]);
    }

    private int getItem(int i) {
        return viewPager.getCurrentItem() + i;
    }

    //  viewpager change listener
    ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            addBottomDots(position);

            if (position == layouts.length - 1) {
                // last page
                btnNext.setText(getString(R.string.done));
                btnPrev.setText(getString(R.string.previous));
            }
            else if (position == 0){
                // first page. don't need the prev button
                btnNext.setText(getString(R.string.next));
            }

            else {
                // still pages are left
                btnNext.setText(getString(R.string.next));
                btnPrev.setText(getString(R.string.previous));

            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }
    };



    /**
     * View pager adapter
     */
    public class MyViewPagerAdapter extends PagerAdapter {
        private LayoutInflater layoutInflater;

        public MyViewPagerAdapter() {
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View view = layoutInflater.inflate(layouts[position], container, false);
            container.addView(view);

            return view;
        }

        @Override
        public int getCount() {
            return layouts.length;
        }

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


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

layout_bo_sign_up_activity.xml为:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:showIn="@layout/layout_bo_sign_up_activity">


    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/layoutDots"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dots_height"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="@dimen/dots_margin_bottom"
        android:gravity="center"
        android:orientation="horizontal">

    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:alpha=".5"
        android:layout_above="@id/layoutDots"
        android:background="@android:color/white" />

    <Button
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:background="@null"
        android:text="@string/next"
        android:textColor="@android:color/white" />

    <Button
        android:id="@+id/btn_prev"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="@null"
        android:text="@string/previous"
        android:textColor="@android:color/white" />

</RelativeLayout>

例如,activity_bo_sign_up.xml是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".BusinessFeatures.BusinessSignUp2"
    android:id="@+id/business_sign_up1">

    <TextView
        android:id="@+id/bo_join_community"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/bo_sign_up_text"
        android:textColor="@color/colorPrimaryDark"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1" />

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/b_email_address"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="360dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginTop="24dp"
        android:hint="@string/email_hint"
        android:textSize="14sp"
        app:counterEnabled="true"
        app:counterMaxLength="30">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/businessEmailEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"/>

    </com.google.android.material.textfield.TextInputLayout>


    <com.google.android.material.textfield.TextInputLayout
    android:id="@+id/b_password"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="360dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="24dp"
    android:layout_marginRight="24dp"
    android:layout_marginStart="24dp"
    android:layout_marginTop="24dp"
    android:hint="@string/password_hint"
    android:textSize="14sp"
    app:counterEnabled="true"
    app:counterMaxLength="30">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/businessPasswordEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"/>

</com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/b_full_name"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="360dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginTop="24dp"
        android:hint="@string/full_name_hint"
        android:textSize="14sp"
        app:counterEnabled="true"
        app:counterMaxLength="30">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/businessFullNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"/>

    </com.google.android.material.textfield.TextInputLayout>


</LinearLayout>

在我的应用中,我使用“查看”页面进行了注册。当我滑动下一个或上一个数据时,但当我在最后一页(第三页)中时,下一个按钮变为完成按钮,当我按完成并尝试...

答案

[尝试以共同的偏好来存储价值。返回该页面时,然后使用共享的首选项值填充edittext。

以上是关于android-数据在viewPage中丢失的主要内容,如果未能解决你的问题,请参考以下文章

viewpager 中的 3 个 android 片段,如何让它们全部存活?

Android中仿淘宝商品详情ViewPager页面数据手动滑动

Android 中ViewPager练习

android 中怎么关掉viewpage的滑动效果

在 ViewPager 中滑动到新页面会导致旧页面丢失状态

ViewPager 未从代码、android、eclipse 更新