延迟加载TabLayout中的元素,Android Studio错误。

huangapple 未分类评论46阅读模式
英文:

Delayed load of elements in TabLayout Android Studio error

问题

My Fragment Page Adapter

public class ViewPagerAdapter extends FragmentPagerAdapter {

    // ... (code remains unchanged)
}

RecyclerView Adapter code

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

    // ... (code remains unchanged)
}

Main Activity Code

public class MainActivity extends AppCompatActivity {

    // ... (code remains unchanged)
}

Lib Fragment

public class LibFragment extends Fragment {

    // ... (code remains unchanged)
}

Fragment Focus Code

public class FragmentFocus extends Fragment {

    // ... (code remains unchanged)
}

Please note that the code provided is in Java and may not contain any translations or explanations. If you have any specific questions about the code or need further assistance, feel free to ask.

英文:

Problem

When I run on the phone, I press lib item(Bottom Menu Library Item). It shows correctly. Then, when I change the fragment (ex: Home Fragment(Bottom Menu Home Item) and reselect lib item(Bottom Menu Library Item) recycler view inside it disappears. To solve I need to wait or relaunch the app. Below my code in Java.

My Fragment Page Adapter

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.ArrayList;
import java.util.List;

public class ViewPagerAdapter extends FragmentPagerAdapter {

    private final List&lt;Fragment&gt; lstFragment = new ArrayList&lt;&gt;(); // this line can cause crashes
    private final List&lt;String&gt; lstTitles = new ArrayList&lt;&gt;();

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

    @Override
    public Fragment getItem(int i) {
        return lstFragment.get(i);
    }

    @Override
    public int getCount() {
        return lstFragment.size();
    }

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

    public void AddFragment(Fragment fragment, String Title){
        lstFragment.add(fragment); // this line can cause crashes
        lstTitles.add(Title);
    }

}

RecyclerView Adapter code

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class RecyclerViewAdapter extends RecyclerView.Adapter&lt;RecyclerViewAdapter.MyViewHolder&gt;{

    Context mContext;
    List&lt;Focus&gt; mData;

    public RecyclerViewAdapter(Context mContext, List&lt;Focus&gt; mData) {
        this.mContext = mContext;
        this.mData = mData;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.card_item_home, viewGroup, false);
        MyViewHolder myViewHolder = new MyViewHolder(v);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
        myViewHolder.txtTitle.setText(mData.get(i).getTitle());
        myViewHolder.imgView.setImageResource(mData.get(i).getImage());
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder{

        TextView txtTitle;
        ImageView imgView;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            txtTitle = itemView.findViewById(R.id.card_view_title);
            imgView = itemView.findViewById(R.id.card_view_image);
        }
    }

}

Main Activity Code

public class MainActivity extends AppCompatActivity {

    private Button music_ImageView;
    private TextView music_title, music_state, music_duration, music_currentTime;
    private SeekBar music_playerSeekbar;
    private MediaPlayer mediaPlayer;
    private Handler handler = new Handler();
    private BottomNavigationView bottomNav;

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

        bottomNav = findViewById(R.id.bottom_nav_menu);
        bottomNav.setOnNavigationItemSelectedListener(navListener);

        /**-------------------------------------------------------------------------**/
        music_ImageView = (Button) findViewById(R.id.music_player_btn);
        music_currentTime = (TextView) findViewById(R.id.textCurrentTime);
        music_duration = (TextView) findViewById(R.id.textTotalDuration);
        music_playerSeekbar = (SeekBar) findViewById(R.id.music_player_seekbar);
        music_title = (TextView) findViewById(R.id.music_player_title);
        music_state = (TextView) findViewById(R.id.music_player_state);
        mediaPlayer = new MediaPlayer();

        music_playerSeekbar.setMax(100);

        music_ImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer.isPlaying()) {
                    handler.removeCallbacks(Updater);
                    mediaPlayer.pause();
                    music_ImageView.setBackgroundResource(R.drawable.ic_pause);
                    music_state.setText(&quot;Pause&quot;);

                } else {
                    mediaPlayer.start();
                    music_ImageView.setBackgroundResource(R.drawable.ic_play);
                    music_state.setText(&quot;Playing&quot;);
                    updateSeekBar();
                }
            }
        });

        prepareMediaPlayer();

        music_playerSeekbar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                SeekBar seekBar = (SeekBar) v;

                int playPosition = (mediaPlayer.getDuration() / 100) * seekBar.getProgress();
                mediaPlayer.seekTo(playPosition);
                music_currentTime.setText(milliSecondsToTimer(mediaPlayer.getCurrentPosition()));
                return true;
            }
        });
        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                music_playerSeekbar.setSecondaryProgress(percent);
            }
        });

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                music_playerSeekbar.setProgress(0);
                music_ImageView.setBackgroundResource(R.drawable.ic_play);
                music_currentTime.setText(R.string.zero);
                music_duration.setText(R.string.zero);
                mediaPlayer.reset();
                prepareMediaPlayer();
            }
        });

        if(savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, new HomeFragment())
                .commit();
        }

        ActionBar actionBar = getSupportActionBar();
        actionBar.setElevation(0);
        actionBar.setTitle(&quot;Brain.Music&quot;);
    }

    private BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;

                    RelativeLayout muz = (RelativeLayout)findViewById(R.id.music_player);

                    ActionBar actionBar;

                    switch (item.getItemId()){
                        case R.id.menu_home: {
                            bottomNav.getMenu().getItem(1).setIcon(R.drawable.ic_favorite_border);
                            selectedFragment = new HomeFragment();
                            actionBar = getSupportActionBar();
                            actionBar.setTitle(&quot;Brain.Music&quot;);
                            muz.setVisibility(View.VISIBLE);
                            }
                            break;
                        case R.id.menu_fav: {
                            item.setIcon(R.drawable.ic_favorite);
                            selectedFragment = new FavFragment();
                            actionBar = getSupportActionBar();
                            actionBar.setTitle(&quot;Favorite&quot;);
                            muz.setVisibility(View.VISIBLE);
                            }
                            break;
                        case R.id.menu_lib: {
                            bottomNav.getMenu().getItem(1).setIcon(R.drawable.ic_favorite_border);
                            selectedFragment = new LibFragment();
                            actionBar = getSupportActionBar();
                            actionBar.setTitle(&quot;Library&quot;);
                            }
                            break;
                    }
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.fragment_container, selectedFragment)
                            .commit();
                    return true;
                }
            };
    private void prepareMediaPlayer(){
        try{
            mediaPlayer.setDataSource(&quot;&quot;);
            mediaPlayer.prepare();
            music_duration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
        }catch (Exception exception){
            Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    private Runnable Updater = new Runnable() {
        @Override
        public void run() {
            updateSeekBar();
            long currentDuration = mediaPlayer.getDuration();
            music_currentTime.setText(milliSecondsToTimer(currentDuration));

        }
    };

    private void updateSeekBar(){
        if ( mediaPlayer.isPlaying()){
            music_playerSeekbar.setProgress((int)((float)mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration() * 100));
            handler.postDelayed(Updater, 1000);
        }
    }

    private String milliSecondsToTimer(long milliSeconds){
        String timerString = &quot;&quot;;
        String secondsString = &quot;&quot;;

        int hours = (int)(milliSeconds / (1000 * 60 * 60));
        int minutes = (int)(milliSeconds % (1000 * 60 * 60) / (1000 * 60));
        int seconds = (int)(milliSeconds % (1000 * 60 * 60) % ((1000 * 60)) / 1000);

        if ( hours &gt; 0 ){
            timerString = hours + &quot;:&quot;;
        }
        if ( seconds &lt; 10 ){
            secondsString = &quot;0&quot; + seconds;
        }else{
            secondsString = &quot;&quot; + seconds;
        }
        timerString = timerString + minutes + &quot;:&quot; + secondsString;
        return timerString;
    }
}

Lib Fragment

import android.app.ActionBar;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

public class LibFragment extends Fragment {

    View v;

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;

    private BottomNavigationView btnNav;
    private Fragment fragment;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_lib, container, false);
        tabLayout = (TabLayout)v.findViewById(R.id.tabLayout);
        viewPager = (ViewPager)v.findViewById(R.id.viewPager);

        /// Adding fragments

        /// Adapter Setting
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);

        tabLayout.getTabAt(2).select();

        return v;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewPagerAdapter = new ViewPagerAdapter(getFragmentManager());
        viewPagerAdapter.AddFragment(new FragmentFocus(), &quot;Focus&quot;); // `FragmentFocus()` should be inside `FragmentPagerAdapter.getItem()`
        viewPagerAdapter.AddFragment(new FragmentSleep(), &quot;Sleep&quot;); // `FragmentSleep()` should be inside `FragmentPagerAdapter.getItem()`
        viewPagerAdapter.AddFragment(new FragmentRelax(), &quot;Relax&quot;); // `FragmentRelax()` should be inside `FragmentPagerAdapter.getItem()`
    }

}

Fragment Focus Code

package com.xcube.demo_nav;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

public class FragmentFocus extends Fragment {

    View v;
    private RecyclerView recyclerView;
    private List&lt;Category&gt;  lstCategory;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.focus_fragment, container, false);

        recyclerView = (RecyclerView)v.findViewById(R.id.recyclerView_library);
        CategoryRecyclerView recyclerViewAdapter = new CategoryRecyclerView(getContext(), lstCategory);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(recyclerViewAdapter);

        return v;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        lstCategory = new ArrayList&lt;&gt;();
        lstCategory.add(new Category(&quot;Lo-FI&quot;, R.drawable.icon_focus));
        lstCategory.add(new Category(&quot;Lo-FI&quot;, R.drawable.icon_focus));
        lstCategory.add(new Category(&quot;Forest&quot;, R.drawable.icon_relax));
    }

}

huangapple
  • 本文由 发表于 2020年4月5日 14:23:47
  • 转载请务必保留本文链接:https://java.coder-hub.com/61038802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定