从菜单更新RecyclerView

时间:2017-02-06 18:37:00

标签: android android-fragments android-recyclerview

我有一个带有两个片段的MainActivity。第二个片段有RecyclerView。在RecyclerView中有TextView(课程名称)和ImageView(显示课程状态,如果已完成或未完成)。单击TextView时,它会通过课程调用另一个Activity。完成课程后,您将返回MainActivity。在那之后,ImageView将从零改为资源'ic_lessondone'。 MainActivity中还有一个菜单。菜单包含“重置课程”项目。按“重置课程”时,所有ImageView都不会显示任何图像。所以有两个问题。 1)如果我这样做,例如,只有第6课。我会把图像'少一些'。当我按下“重置课程”时,图像将消失。但当我再次返回菜单并按“重置课程”时,图像将再次出现并上升到上一课(第5节)。 2)如果我关闭显示,图像也会出现在上一课,直到0。 看来我的onResume有问题。 请帮帮我。

public class MainActivity extends AppCompatActivity
{
    private DrawerLayout mDrawerLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setDisplayHomeAsUpEnabled(true);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        if (navigationView != null)
        {
            setupDrawerContent(navigationView);
        }

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        if (viewPager != null)
        {
            setupViewPager(viewPager);
        }

        // Круглая кнопка
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view)
                {
                    Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                }
            });

        //  Картинки для табов  
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.getTabAt(0).setIcon(R.drawable.ic_home);
        tabLayout.getTabAt(1).setIcon(R.drawable.ic_lessons);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.sample_actions, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
        switch (AppCompatDelegate.getDefaultNightMode())
        {
            case AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM:
                menu.findItem(R.id.menu_night_mode_system).setChecked(true);
                break;
            case AppCompatDelegate.MODE_NIGHT_AUTO:
                menu.findItem(R.id.menu_night_mode_auto).setChecked(true);
                break;
            case AppCompatDelegate.MODE_NIGHT_YES:
                menu.findItem(R.id.menu_night_mode_night).setChecked(true);
                break;
            case AppCompatDelegate.MODE_NIGHT_NO:
                menu.findItem(R.id.menu_night_mode_day).setChecked(true);
                break;
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                return true;
            case R.id.menu_night_mode_system:
                setNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
                break;
            case R.id.menu_night_mode_day:
                setNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                break;
            case R.id.menu_night_mode_night:
                setNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                break;
            case R.id.menu_night_mode_auto:
                setNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setNightMode(@AppCompatDelegate.NightMode int nightMode)
    {
        AppCompatDelegate.setDefaultNightMode(nightMode);

        if (Build.VERSION.SDK_INT >= 11)
        {
            recreate();
        }
    }

    private void setupViewPager(ViewPager viewPager)
    {
        Adapter adapter = new Adapter(getSupportFragmentManager());
        adapter.addFragment(new Fragment(), "");
        adapter.addFragment(new LessonsListFragment(), "");
        viewPager.setAdapter(adapter);
    }

    // Главное меню
    private void setupDrawerContent(NavigationView navigationView)
    {
        navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem)
                {
                    menuItem.setChecked(true);
                    if (menuItem.getTitle().equals("Reset lessons"))
                    {
                        // Обнуляем файл с рузультатами уроков
                        LessonsListFragment.sLessonsPref.edit().clear().commit();             
                        // Перерисовываем весь писок уроков                    
                        LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
                    }
                    mDrawerLayout.closeDrawers();
                    return true;
                }
            });
    }

    static class Adapter extends FragmentPagerAdapter
    {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

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

        public void addFragment(Fragment fragment, String title)
        {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        // Получаем конкретный фрагмент
        @Override
        public Fragment getItem(int position)
        {
            return mFragments.get(position);
        }

        // Количество фрагментов для viewpager (2)
        @Override
        public int getCount()
        {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position)
        {
            return mFragmentTitles.get(position);
        }
    }
}

片段

public class LessonsListFragment extends Fragment
{
    // Уроки
    // static private Map<String,?> mLessonsKeys ;
    static SharedPreferences  sLessonsPref;
    static RecyclerView rv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        loadSharedPreferenses();
        rv = (RecyclerView) inflater.inflate(R.layout.fragment_cheese_list, container, false);
        setupRecyclerView(rv);
        return rv;
    }

    // Загружаем список пройденных уроков
    public void loadSharedPreferenses()
    {
        sLessonsPref = this.getActivity().getSharedPreferences("LessonsResults", Context.MODE_PRIVATE);
    }

    // Количество строк в листе
    private void setupRecyclerView(RecyclerView recyclerView)
    {
        recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
        recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), getRandomSublist(Cheeses.sCheeseStrings, Cheeses.sCheeseStrings.length)));
    }

    // Задаем Строки
    private List<String> getRandomSublist(String[] array, int amount)
    {
        ArrayList<String> list = new ArrayList<>(amount);
        //Random random = new Random();
        while (list.size() < amount)
        {
            list.add(array[list.size()]);
        }
        return list;
    }


    //Отработка перерисования окна, при возврате к ней
    @Override
    public void onResume()
    {
        super.onResume();
        //loadSharedPreferenses();
        //Toast.makeText(null, "Refreshed", Toast.LENGTH_SHORT).show();
        if (rv.getAdapter() != null)
        {
            rv.getAdapter().notifyDataSetChanged();
        }
    }


// Адаптер 
    public static class SimpleStringRecyclerViewAdapter
    extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder>
    {

        private final TypedValue mTypedValue = new TypedValue();
        private int mBackground;
        private List<String> mValues;

        public static class ViewHolder extends RecyclerView.ViewHolder
        {
            // Номер урока, передается в webactivity
            public int mLessonNumber;

            public final View mView;
            public final ImageView mImageView;
            public final TextView mTextView;

            public ViewHolder(View view)
            {
                super(view);
                mView = view;
                mImageView = (ImageView) view.findViewById(R.id.avatar);
                mTextView = (TextView) view.findViewById(android.R.id.text1);
            }

            @Override
            public String toString()
            {
                return super.toString() + " '" + mTextView.getText();
            }
        }

        public String getValueAt(int position)
        {
            return mValues.get(position);
        }

        public SimpleStringRecyclerViewAdapter(Context context, List<String> items)
        {
            context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
            mBackground = mTypedValue.resourceId;
            mValues = items;

        }

        // Создаем холдер с полезной нагрузкой
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item, parent, false);
            view.setBackgroundResource(mBackground);
            return new ViewHolder(view);
        }

        //Создаем список уроков
        @Override
        public void onBindViewHolder(final ViewHolder holder, int position)
        {

            holder.mLessonNumber = position + 1;
            // Увеличиваем позицион на 1 что не было 0 урока
            holder.mTextView.setText((position + 1) + " " + mValues.get(position));

            // Если урок пройден
            String finished = sLessonsPref.getString((position + 1) + "", "");
            if (finished.equals("1"))
            {
                // Меняем его цвет
                //holder.mTextView.setTextColor(R.color.white);
                Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
                    //.load(Cheeses.getRandomCheeseDrawable())
                    .fitCenter()
                    .into(holder.mImageView);
                Log.d("Glide", "Work");
            }
            else
            {
                holder.mTextView.setTextColor(R.color.black);
                // holder.mImageView.setVisibility(View.GONE);
            }

            // Вызов WebActivity
            holder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v)
                    {
                        Context context = v.getContext();
                        Intent intent = new Intent(context, WebActivity.class);
                        // Передаем вебвью номер урока и запускаем ее
                        intent.putExtra(WebActivity.EXTRA_NAME, holder.mLessonNumber);
                        context.startActivity(intent);
                    }
                });
        }
        // Определяем количество выводимых строк
        @Override
        public int getItemCount()
        {
            return mValues.size();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

在适配器中实现一个reset()方法,将所有项目标记为&#34;未完成&#34;然后尝试:

LessonsListFragment.rv.getAdapter().reset();
LessonsListFragment.rv.getAdapter().notifyDataSetChanged();

而不是:

LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());

onNavigationItemSelected内。

此外,你不应该使用静态变量(如static RecyclerView rv),使用private变量与吸气剂

答案 1 :(得分:0)

问题出在其他声明中。我在那里添加了这段代码,现在还可以。 notifydatachanged在导航视图中正常工作

 if (finished.equals("1"))
            {
                // Меняем его цвет
                //holder.mTextView.setTextColor(R.color.white);
                Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)

                    .fitCenter()
                    .into(holder.mImageView);
                Log.d("Glide", "Work");
            }
            else
            {
                        Glide.with(holder.mImageView.getContext()).load(R.color.white)
                    .fitCenter()
                    .into(holder.mImageView);
          holder.mTextView.setTextColor(R.color.black);

            }