FragmentStatePagerAdapter

FragmentStatePagerAdapter

我有一个应用程序,其中包含五个类别的抽屉。每个类别都会打开一个选项卡式的分页器(取决于所选类别),并显示用户可以滑动的问题。我遇到的问题是,当选择答案时,例如说类别1,问题0-相同的答案出现在类别2,问题0和类别3,问题0等上。无论我调用clearchecked()多少次,答案都会在我尚未回答的类别上重复出现。如果我将clearchecked()放在onResume()中,这确实会停止这种效果,但会导致每次擦除片段时都删除所有答案。

我已经确保实现notifydatasetchanged / return position_none(这帮助我解决了根据类别更改问题的部分)。据我了解,通过使用FragmentStatePagerAdapter而不是FragmentPagerAdapter,视图/片段将被破坏,因此在重新创建时不会保留视图状态?

这些疲劳的眼睛将不胜感激。

FragmentStatePagerAdapter:

    public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
SharedPreferences prefs;
int row;
int form;
Context mContext;


public void getContext(Context context) {
    prefs = PreferenceManager.getDefaultSharedPreferences((context));
    mContext = context;
}


public SectionsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    //form = category #1-5
    return QuestionFragment.newInstance(position, form, mContext);

}

@Override
public int getCount() {

    row = prefs.getInt("Valid", 0);
    return prefs.getInt("TotalQuestions_" + row, 3);

}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}


public void getNumber(int n) {
    form = n;
}


}

DrawerActivity:

    public class Drawer extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
ViewPager mViewPager;
SectionsPagerAdapter mSectionsPagerAdapter;
Blog blog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_drawer);
    mViewPager = (ViewPager) findViewById(R.id.container);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Hello! Swipe between screens!", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    mSectionsPagerAdapter.getContext(getApplicationContext());


    FragmentManager fm = getSupportFragmentManager();
    blog = new Blog();
    fm.beginTransaction().replace(R.id.container1, blog).commit();


}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.drawer, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    FragmentManager fm = getSupportFragmentManager();

    int id = item.getItemId();

    if (id == R.id.leadership) {
        mSectionsPagerAdapter.getNumber(0);
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setAdapter(mSectionsPagerAdapter);
        if(fm.findFragmentById(R.id.container1)!=null) {
            fm.beginTransaction().remove(fm.findFragmentById(R.id.container1)).commit();
        }


    } else if (id == R.id.management) {
        mSectionsPagerAdapter.getNumber(1);
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setAdapter(mSectionsPagerAdapter);
        if(fm.findFragmentById(R.id.container1)!=null) {
            fm.beginTransaction().remove(fm.findFragmentById(R.id.container1)).commit();
        }


    } else if (id == R.id.wellbeing) {
        mSectionsPagerAdapter.getNumber(2);
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setAdapter(mSectionsPagerAdapter);
        if(fm.findFragmentById(R.id.container1)!=null) {
            fm.beginTransaction().remove(fm.findFragmentById(R.id.container1)).commit();
        }


    } else if (id == R.id.person_growth) {
        mSectionsPagerAdapter.getNumber(3);
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setAdapter(mSectionsPagerAdapter);
        if(fm.findFragmentById(R.id.container1)!=null) {
            fm.beginTransaction().remove(fm.findFragmentById(R.id.container1)).commit();
        }


    } else if (id == R.id.strategy) {
        mSectionsPagerAdapter.getNumber(4);
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setAdapter(mSectionsPagerAdapter);
        if(fm.findFragmentById(R.id.container1)!=null) {
            fm.beginTransaction().remove(fm.findFragmentById(R.id.container1)).commit();
        }

    } else if (id == R.id.blogentry) {
        fm.beginTransaction().replace(R.id.container1, new Blog()).commit();

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}


问题片段:

    public class QuestionFragment extends Fragment {
/**
 * The fragment argument representing the section number for this
 * fragment.
 */
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String FORM = "form";
public RadioGroup selected;
private boolean check1;
private boolean check2;
private boolean check3;
private boolean check4;
public int button;
String[] convertedQuestions;
public static Context mContext;
Bundle answers = new Bundle();


/**
 * Returns a new instance of this fragment for the given section
 * number.
 */
public static QuestionFragment newInstance(int sectionNumber, int form, Context context) {
    QuestionFragment fragment = new QuestionFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    args.putInt(FORM, form);
    fragment.setArguments(args);
    mContext = context;
    return fragment;
}


public QuestionFragment() {
    super();
}


@Override
public void setRetainInstance(boolean retain) {
    super.setRetainInstance(false);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());

    //GETS THE QUESTION NAMES
    //convertedQuestions = Array of questions
    Set<String> rawQuestions = prefs.getStringSet("Questions_" + getArguments().getInt(FORM) + "", null);
    Converter(rawQuestions);

    //GETS THE CORRESPONDING LAYOUT
    //Types = set of question types
    Set<String> types = prefs.getStringSet("Types_" + getArguments().getInt(FORM) + "", null);
    GetQuestionLayout getDaLayouts = new GetQuestionLayout();
    View rootView = inflater.inflate(getDaLayouts.sort(types, getArguments().getInt(ARG_SECTION_NUMBER)), container, false);

    TextView textView = (TextView) rootView.findViewById(R.id.section_label);
    String fullQ = convertedQuestions[getArguments().getInt(ARG_SECTION_NUMBER)];
    textView.setText(fullQ.substring(4, fullQ.length()));


    //IF LINEAR SCALE
    if (getDaLayouts.sort(types, getArguments().getInt(ARG_SECTION_NUMBER)) == R.layout.linear_scale) {
        selected = (RadioGroup) rootView.findViewById(R.id.answer);
        selected.clearCheck();


        }
     //IF MULTIPLE CHOICE
    } else if (getDaLayouts.sort(types, getArguments().getInt(ARG_SECTION_NUMBER)) == R.layout.multiple_choice) {
        CheckBox a = (CheckBox) rootView.findViewById(R.id.c1);
        a.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    check1 = true;
                } else {
                    check1 = false;
                }
            }
        });
        CheckBox b = (CheckBox) rootView.findViewById(R.id.c2);
        b.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    check2 = true;
                } else {
                    check2 = false;
                }
            }
        });
        CheckBox c = (CheckBox) rootView.findViewById(R.id.c3);
        c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    check3 = true;
                } else {
                    check3 = false;
                }
            }
        });
        CheckBox d = (CheckBox) rootView.findViewById(R.id.c4);
        d.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean       isChecked) {
                if (isChecked) {
                    check4 = true;
                } else {
                    check4 = false;
                }
            }
        });
    return rootView;
}

public String[] Converter(Set<String> set) {
    convertedQuestions = new String[set.size()];
    TreeSet<String> sorted = new TreeSet<>();
    for (String sort : set) {
        sorted.add(sort);
    }
    sorted.toArray(convertedQuestions);


    return convertedQuestions;
}


}

最佳答案

我想到了。每次单击抽屉类别时,我需要创建一个FragmentStatePagerAdapter的新实例,因此刷新了片段中的视图状态!

     if (id == R.id.leadership) {
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mSectionsPagerAdapter.getContext(getApplicationContext());
        mSectionsPagerAdapter.getNumber(0);
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setAdapter(mSectionsPagerAdapter);
        if(fm.findFragmentById(R.id.container1)!=null) {
            fm.beginTransaction().remove(fm.findFragmentById(R.id.container1)).commit();
        }


    } else if (id == R.id.management) {
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mSectionsPagerAdapter.getContext(getApplicationContext());
        mSectionsPagerAdapter.getNumber(1);
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setAdapter(mSectionsPagerAdapter);
        if(fm.findFragmentById(R.id.container1)!=null) {
            fm.beginTransaction().remove(fm.findFragmentById(R.id.container1)).commit();
        }


    } else if (id == R.id.wellbeing) {
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mSectionsPagerAdapter.getContext(getApplicationContext());
        mSectionsPagerAdapter.getNumber(2);
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setAdapter(mSectionsPagerAdapter);
        if(fm.findFragmentById(R.id.container1)!=null) {
            fm.beginTransaction().remove(fm.findFragmentById(R.id.container1)).commit();
        }


    } else if (id == R.id.person_growth) {
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mSectionsPagerAdapter.getContext(getApplicationContext());
        mSectionsPagerAdapter.getNumber(3);
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setAdapter(mSectionsPagerAdapter);
        if(fm.findFragmentById(R.id.container1)!=null) {
            fm.beginTransaction().remove(fm.findFragmentById(R.id.container1)).commit();
        }


    } else if (id == R.id.strategy) {
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mSectionsPagerAdapter.getContext(getApplicationContext());
        mSectionsPagerAdapter.getNumber(4);
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setAdapter(mSectionsPagerAdapter);
        if(fm.findFragmentById(R.id.container1)!=null) {
            fm.beginTransaction().remove(fm.findFragmentById(R.id.container1)).commit();
        }

关于android - FragmentStatePagerAdapter不会破坏旧的 View 状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36191061/

10-10 20:11