FragmentStatePagerAdapter不会破坏旧视图状态

时间:2016-03-24 00:09:55

标签: android android-fragments android-viewpager viewstate

我的应用程序有一个抽屉,里面有五个类别。每个类别打开一个选项卡式viewpager(取决于所选的类别)并显示用户可以刷卡的问题。我遇到的问题是当选择答案时 - 让我们说类别1,问题0-同样的答案出现在类别2,问题0& category3,问题0,依此类推。无论我多少次打电话给clearchecked(),答案都会重复我尚未回答的类别。如果我在onResume()中放入clearchecked(),这会停止此效果,但每次刷片段时都会删除所有答案。

我确保实现了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;
}
}

QuestionFragments:

    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;
}

}

1 个答案:

答案 0 :(得分:1)

我把它弄清楚了。每次单击抽屉类别时,我都需要创建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();
        }