Android片段更新问题

时间:2016-04-24 05:39:52

标签: android android-fragments

我使用tablayout有三个片段。问题是我在第一个片段中保存数据并希望在第二个片段中显示数据但第二​​个片段在点击或滑动到第二个片段时不会更新,因为片段由于默认偏移限制而不再创建1.当我再次重新启动应用程序时,显示数据。任何解决方案都受到高度赞赏。

//我的MainActivity代码

public class MainActivity extends AppCompatActivity
{
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private int[] tabIcons = {
            R.drawable.calender,
            R.drawable.favourite,
            R.drawable.setting_icon
    };

    PagerAdapter pagerAdapter;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayShowTitleEnabled(false);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        pagerAdapter =  new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
        viewPager.setAdapter(pagerAdapter);
       // viewPager.setOffscreenPageLimit(0);

        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.getTabAt(0).setIcon(R.drawable.calender_hover);


        for (int i = 0; i < tabLayout.getTabCount(); i++)
        {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(pagerAdapter.getTabView(i));
        }

    }

    class PagerAdapter extends FragmentStatePagerAdapter
    {

        String tabTitles[] = new String[] { "Tab One", "Tab Two", "Tab Three", };

        private int[] tabIcons = { R.drawable.tab_selector_calendar, R.drawable.tab_selector_favorite, R.drawable.tab_selector_settings
        };

        Context context;

        public PagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }

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

        @Override
        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    return new FragmentAyah();
                case 1:
                    return new FragmentFavorite();
                case 2:
                    return new FragmentSettings();
            }

            return null;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // Generate title based on item position
           // return tabTitles[position];
            return null;
        }

        public View getTabView(int position) {
            View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
            ImageView imgView = (ImageView) tab.findViewById(R.id.imgView);

            imgView.setBackgroundResource(tabIcons[position]);


            //  TextView tv = (TextView) tab.findViewById(R.id.custom_text);
            // tv.setText(tabTitles[position]);
            return tab;
        }

    }

}
 and Fragment code

// Tab 1 FragmentAyah代码

public class FragmentAyah extends Fragment
{
    private RecyclerView recyclerView;
    private List<Ayat> ayatList = new ArrayList<>();
    private AyatAdapter ayatAdapter;
    DBHelper dbHelperA;
    List<AyatVariables> datalist = new ArrayList<AyatVariables>();
    String formattedDate = "";
    SimpleDateFormat df;
    private Calendar c;

    public FragmentAyah()
    {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_ayah, null);

        recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);
        ayatAdapter = new AyatAdapter(ayatList,getActivity());

        dbHelperA = new DBHelper(getActivity());

        c = Calendar.getInstance();
        df = new SimpleDateFormat("yyyy-MM-dd");
        formattedDate = df.format(c.getTime());

        getAllValuesFromDB();

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
        recyclerView.setAdapter(ayatAdapter);
        ayatAdapter.notifyDataSetChanged();

        return root;
    }

    private void prepareMovieData() {
        // AyatVariables ayat = new AyatVariables("Surah Al-Fatiha","Ayat","1",":11","Translation11");
for (int i = 0; i < datalist.size(); i++) {
                    Ayat ayat = new Ayat(datalist.get(i).getID(), datalist.get(i).getSURAH_NAME(),
                            datalist.get(i).getTEXTS(), datalist.get(i).getSURAH(),
                            datalist.get(i).getAYA(), datalist.get(i).getEN_TRANSLATION(),
                            datalist.get(i).getDATES());

                    ayatList.add(ayat);

                ayatAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
        Log.e("onDestroyView======>","onDestroyView");
        ayatAdapter.notifyDataSetChanged();
        ayatList.clear();
    }

    public void getAllValuesFromDB()
    {
        try {
            dbHelperA.createDataBase();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        datalist.clear();
        datalist = dbHelperA.getDataWithAllTranslation(formattedDate);
       // Log.e("datasize=========>",""+datalist.size());
        dbHelperA.close();

        prepareMovieData();
    }

}

// Tab 2 FragmentFavorite代码

public class FragmentFavorite extends Fragment {

    private RecyclerView recyclerView;
    private List<FAyat> ayatList = new ArrayList<>();
    private AyatFAdapter ayatAdapter;
    DBHelper dbHelperA;
    DBHelper2 dbHelperF;
    List<AyatVariables> datalist = new ArrayList<AyatVariables>();
    List<FavVariables> fVar = new ArrayList<FavVariables>();
    String formattedDate = "";
    SimpleDateFormat df;
    private Calendar c;

    public FragmentFavorite() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_favorits, null);
        recyclerView = (RecyclerView) root.findViewById(R.id.frecycler_view);
        ayatAdapter = new AyatFAdapter(ayatList, getActivity());

        dbHelperA = new DBHelper(getActivity());
        dbHelperF = new DBHelper2(getActivity());

        c = Calendar.getInstance();
        df = new SimpleDateFormat("yyyy-MM-dd");
        formattedDate = df.format(c.getTime());

        getAllValuesFromDB();

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(ayatAdapter);
        ayatAdapter.notifyDataSetChanged();

        return root;
    }

    private void prepareMovieData() {
        // AyatVariables ayat = new AyatVariables("Surah Al-Fatiha","Ayat","1",":11","Translation11");

       for (int i = 0; i < datalist.size(); i++) {
                    FAyat ayat = new FAyat(datalist.get(i).getID(), datalist.get(i).getSURAH_NAME(),
                            datalist.get(i).getTEXTS(), datalist.get(i).getSURAH(),
                            datalist.get(i).getAYA(), datalist.get(i).getEN_TRANSLATION(),
                            datalist.get(i).getDATES());

                    ayatList.add(ayat);

                            ayatAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ayatList.clear();
    }

    public void getAllValuesFromDB()
    {
        getIDfromFav();

        try {
            dbHelperA.createDataBase();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        for (int i = 0; i<fVar.size();i++) {
           // datalist = dbHelperA.getAllDataForFav(fVar.get(i).getFavID());
            datalist.add(dbHelperA.getAllDataForFav(fVar.get(i).getFavID()));

            Log.e("datasize=========>",""+datalist.size());
        }
        dbHelperA.close();

        prepareMovieData();
    }

    public void getIDfromFav()
    {
        fVar.clear();
        fVar = dbHelperF.getAllFav();
        Log.e("fVar--size",""+fVar.size());
        dbHelperF.close();
    }

}

1 个答案:

答案 0 :(得分:0)

您可以通过多种方式使用非耦合类来更改数据。以下是广播接收器的示例代码:

在片段1中,当某些数据发生变化时,请执行此操作,

Intent intent = new Intent("my-event");
// add data
intent.putExtra("message", "data"); // This data can be anything which is changed. You can also use SharedPreference and can remove that after using it
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

现在,在片段2中,首先你需要将这个片段注册为接收者,

@Override
public void onResume() {
super.onResume();

// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("my-event"));
}

现在,注册后,您必须处理接收意图

// handler for received Intents for the "my-event" event 
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent or from SharedPreference in that case
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
// In your case, you have to update the views or values in this method
 }
};

暂停监听onPause以避免空上下文

@Override
protected void onPause() {
// Unregister since the fragment is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}