如何刷新/重新加载选项卡式活动的焦点选项卡

时间:2017-01-11 17:45:12

标签: android android-fragments tabs

我正在尝试使我的标签式活动内容动态更改,取决于其他标签中的用户选择。

所有标签使用相同的片段。只有视图中的内容应该更改(在本例中为ListView)

现在主要的问题是当我做出选择时(单击ListView中的某一行),下一个选项卡会显示所有内容,而不是根据我在上一个选项卡中的选择过滤数据,但是当我点击时一个非邻居选项卡,然后返回,选项卡被过滤,就像我想要的那样。

根据我的理解,活动会加载当前选项卡的邻居选项卡,即使这些选项卡没有聚焦,这也是我获得默认结果的原因。

简化事情:

然后我从ListView中选择一行,焦点自动转到下一个标签。

listView将向我显示默认语句,就像我没有选择任何内容一样。但是,如果我将焦点移动到第四个选项卡,然后再次返回到第二个选项卡,listView将按照我想要的方式进行过滤

这是我的代码

public class Catalog_actbartabs extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;
public static String PACKAGE_NAME;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    PACKAGE_NAME = getApplicationContext().getPackageName();

}


public void setCurrentItem(int item, boolean smoothScroll) {
    mViewPager.setCurrentItem(item, smoothScroll);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_catalog_actbartabs, 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);
}


/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    protected ClogListAdapter2 clogListAdapter2;
    protected ArrayList<String[]> stringArrayList;
    protected static String topic = null;
    protected static String rName = null;
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */

    private static final String ARG_SECTION_NUMBER = "section_number";
    private static final String EXTRA_ITEM_INFO = "com.dstudio.dvir.EXTRA_ITEM_INFO";

    public PlaceholderFragment() {
    }

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


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

        View rootView;
        rootView = inflater.inflate(R.layout.fragment_catalog, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));


        try {
            if (getArguments().getInt(ARG_SECTION_NUMBER) == 1)
                stringArrayList = Utils.getNamesList(super.getContext());
            else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2)
                stringArrayList = Utils.getTopicsList(super.getContext(), rName);
            else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3)
                stringArrayList = Utils.getClassesList(super.getContext(), rName, topic);
            else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4)
                stringArrayList = Utils.getFilesList(super.getContext());
        } catch (Throwable t) {
            Toast.makeText(super.getContext(), "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
        }


        if (savedInstanceState != null) {
            String[] values = savedInstanceState.getStringArray("myKey");
            if (values != null) {
                stringArrayList = ClogListAdapter2.bmListFromArray(values);
            }
        } else if (stringArrayList == null) {
            stringArrayList = new ArrayList<String[]>();
        }

        clogListAdapter2 = new ClogListAdapter2(super.getContext(), stringArrayList, getArguments().getInt(ARG_SECTION_NUMBER));
        ListView listV = (ListView) rootView.findViewById(R.id.listView);
        listV.setAdapter(clogListAdapter2);
        listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
                    if (clogListAdapter2.getItem(position)[0].equals("All"))
                        rName = null;
                    else rName = clogListAdapter2.getItem(position)[0];
                    topic = null;
                } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
                    if (clogListAdapter2.getItem(position)[0].equals("All"))
                        topic = null;
                    else topic = clogListAdapter2.getItem(position)[0];
                } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4) {
                    Intent intent = new Intent(parent.getContext(), AudioPlayerActivity.class);
                    intent.putExtra(EXTRA_ITEM_INFO, clogListAdapter2.getItem(position));
                    startActivityForResult(intent, 1);
                }

                ((Catalog_actbartabs) getActivity()).setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER), true);
            }
        });
        return rootView;
    }
}


public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 4 total pages.
        return 4;
    }


    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "page 1";
            case 1:
                return "page 2";
            case 2:
                return "page 3";
            case 3:
                return "page 4";
        }
        return null;
    }
}
}

更新

来自@AmeyShirke的工作解决方案

我将var _hasLoadedOnce= false;添加到PlaceholderFragment类的其他变量中:

public static class PlaceholderFragment extends Fragment {
    protected ClogListAdapter2 clogListAdapter2;
    protected ArrayList<String[]> stringArrayList;
    protected View rootView;
    protected static String topic = null;
    protected static String rName = null;
    private boolean _hasLoadedOnce= false;
    //Rest of the code
}

现在所有数据设置代码都在setUserVisibleHint()内,而不更改_hasLoadedOnce所以它看起来像这样:

        @Override
    public void setUserVisibleHint(boolean isFragmentVisible_) {
        super.setUserVisibleHint(true);
        if (this.isVisible()) {
            // we check that the fragment is becoming visible
            if (isFragmentVisible_ && !_hasLoadedOnce) {

                Log.i("visable: ", getArguments().getInt(ARG_SECTION_NUMBER)+"");
                try {
                    if (getArguments().getInt(ARG_SECTION_NUMBER) == 1)
                        stringArrayList = Utils.getNamesList(super.getContext());
                    else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2)
                        stringArrayList = Utils.getTopicsList(super.getContext(), rName);
                    else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3)
                        stringArrayList = Utils.getClassesList(super.getContext(), rName, topic);
                    else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4)
                        stringArrayList = Utils.getFilesList(super.getContext());
                } catch (Throwable t) {
                    Toast.makeText(super.getContext(), "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
                }

                clogListAdapter2 = new ClogListAdapter2(super.getContext(), stringArrayList, getArguments().getInt(ARG_SECTION_NUMBER));
                ListView listV = (ListView) rootView.findViewById(R.id.listView);
                listV.setAdapter(clogListAdapter2);
                listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        // TODO: 23/12/2016 remember to also give the needed info to get the asked next category
                        if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
                            if (clogListAdapter2.getItem(position)[0].equals("All"))
                                rName = null;
                            else rName = clogListAdapter2.getItem(position)[0];
                            topic = null;
                        } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
                            if (clogListAdapter2.getItem(position)[0].equals("All"))
                                topic = null;
                            else topic = clogListAdapter2.getItem(position)[0];
                        } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4) {
                            Intent intent = new Intent(parent.getContext(), AudioPlayerActivity.class);
                            intent.putExtra(EXTRA_ITEM_INFO, clogListAdapter2.getItem(position));
                            startActivityForResult(intent, 1);
                        }

                        ((Catalog_actbartabs) getActivity()).setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER), true);
                    }
                });
                //Notify that _hasLoadedOnce = true; is now gone
            }
        }
    }

我还在活动的mViewPager.setOffscreenPageLimit(3);中添加了行onCreate(),因为如果我在第一次过滤后选择直接转到第四个标签,则不会对其进行过滤,这样活动就会过滤它正确。

1 个答案:

答案 0 :(得分:0)

这是ViewPager的默认行为。要仅加载单个标签,请使用:

mViewPager.setOffscreenPageLimit(1);

如果这不起作用,那么你必须创建自己的ViewPager子类并覆盖以下方法:

private boolean _hasLoadedOnce= false; // your boolean field

@Override
public void setUserVisibleHint(boolean isFragmentVisible_) {
    super.setUserVisibleHint(true);


    if (this.isVisible()) {
        // we check that the fragment is becoming visible
        if (isFragmentVisible_ && !_hasLoadedOnce) {
            //your code here
            _hasLoadedOnce = true;
        }
    }
}