Проблема
Когда я бегу по телефону, я нажимаю элемент lib ( Элемент библиотеки нижнего меню ). Это показывает правильно. Затем, когда я изменяю фрагмент (например, «Домашний фрагмент» ( Элемент «Домой» нижнего меню * ) и повторно выбираю элемент lib ( Элемент библиотеки нижнего меню ), вид изнутри переработчика исчезает. Для его решения мне нужно подождать или перезапустить приложение. Ниже мой код в Java.
Адаптер страницы моего фрагмента
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<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
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);
lstTitles.add(Title);
}
}
Код адаптера RecyclerView
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<RecyclerViewAdapter.MyViewHolder>{
Context mContext;
List<Focus> mData;
public RecyclerViewAdapter(Context mContext, List<Focus> 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);
}
}
}
Основной код активности
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("Pause");
} else {
mediaPlayer.start();
music_ImageView.setBackgroundResource(R.drawable.ic_play);
music_state.setText("Playing");
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();
}
});
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new HomeFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
actionBar.setElevation(0);
actionBar.setTitle("Brain.Music");
}
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("Brain.Music");
muz.setVisibility(View.VISIBLE);
}
break;
case R.id.menu_fav: {
item.setIcon(R.drawable.ic_favorite);
selectedFragment = new FavFragment();
actionBar = getSupportActionBar();
actionBar.setTitle("Favorite");
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("Library");
}
break;
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, selectedFragment)
.commit();
return true;
}
};
private void prepareMediaPlayer(){
try{
mediaPlayer.setDataSource("");
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 = "";
String secondsString = "";
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 > 0 ){
timerString = hours + ":";
}
if ( seconds < 10 ){
secondsString = "0" + seconds;
}else{
secondsString = "" + seconds;
}
timerString = timerString + minutes + ":" + secondsString;
return timerString;
}
}
Фрагмент Lib
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(), "Focus");
viewPagerAdapter.AddFragment(new FragmentSleep(), "Sleep");
viewPagerAdapter.AddFragment(new FragmentRelax(), "Relax");
}
}
Фокусный код фрагмента
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<Category> 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<>();
lstCategory.add(new Category("Lo-FI", R.drawable.icon_focus));
lstCategory.add(new Category("Lo-FI", R.drawable.icon_focus));
lstCategory.add(new Category("Forest", R.drawable.icon_relax));
}
}