fragment 的切换并且解决重叠的问题

package com.dofun.dofunmusic.main;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dofun.dofunmusic.utils.OkHttpUtils;
import com.dofun.dofunmusic.utils.Utils;
import com.dofun.dofunmusic.view.fragment.NewSongsRankFragment;
import com.dofun.dofunmusic.view.fragment.PersonalRecommendFragment;
import com.dofun.dofunmusic.view.fragment.RecommandSongsFragment;
import com.ximalaya.ting.android.opensdk.constants.DTransferConstants;
import com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest;
import com.ximalaya.ting.android.opensdk.datatrasfer.IDataCallBack;
import com.ximalaya.ting.android.opensdk.model.album.AlbumList;
import com.ximalaya.ting.android.opensdk.model.album.SearchAlbumList;
import com.ximalaya.ting.android.opensdk.model.category.CategoryList;
import com.ximalaya.ting.android.opensdk.model.tag.TagList;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class CloudMusicActivity extends AppCompatActivity {

    private static final String TAG = "CloudMusicActivity";

    @Bind(R.id.recommendation_id)
    TextView recommendationId;
    @Bind(R.id.recommend_songs_id)
    TextView recommendSongsId;
    @Bind(R.id.new_song_list_id)
    TextView newSongListId;
    @Bind(R.id.search)
    EditText search;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.details)
    FrameLayout details;
    @Bind(R.id.recommend_first_imv)
    ImageView recommendFirstImv;
    @Bind(R.id.recommend_second_imv)
    ImageView recommendSecondImv;
    @Bind(R.id.recommend_third_imv)
    ImageView recommendThirdImv;
    @Bind(R.id.test)
    Button test;
    @Bind(R.id.cloud_rootView)
    LinearLayout cloudRootView;

    private FragmentManager fragmentManager;
    private PersonalRecommendFragment personalRecommendFragment;
    private RecommandSongsFragment recommandSongsFragment;
    private NewSongsRankFragment newSongsRankFragment;
    public static final int FRAGMENT_ONE = 0;
    public static final int FRAGMENT_TWO = 1;
    public static final int FRAGMENT_THREE = 2;

    private boolean flag_dn = false;
    private boolean dnflag = false;
    private Handler handler = new Handler();
    private static SharedPreferences sharedPreferences;

    private Context mContext;
    private FinalBitmap mFinalBitmap;
    private FinalHttp mFinalHttp;
    private XmPlayerManager mPlayerManager;
    private CommonRequest mXimalaya;
    private String mAppSecret = "3e35490f09dd408efac49604a9a98cc9";
    private CategoryList mCategoryList = null;
    private final int ALL_CATEGORY = 1;
    private final int ALL_CATEGORY_ERROR = 1002;
    private final int GETMUSICTAGLIST = 1003;
    private final int SearchAlbumData = 1004;
    private final int SearchDataError = 1005;
    private TagList mMusicTagList = new TagList();
    private SearchAlbumList mSearchAlbumList = new SearchAlbumList();


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ALL_CATEGORY:
                    if ((mCategoryList != null) && (mCategoryList.getCategories().size() > 0)) {
                        for (int i = 0; i < mCategoryList.getCategories().size(); i++) {
                            Log.e(TAG, "mCategoryList.getCategories().get(" + i + ")=" + mCategoryList.getCategories().get(i));
                        }
                    }
                    break;
                case ALL_CATEGORY_ERROR:
                    Toast.makeText(CloudMusicActivity.this, "获取云音乐失败,稍后重试!", Toast.LENGTH_SHORT).show();
                    break;
                case GETMUSICTAGLIST:



                    Log.e(TAG, "------获取MusicTagList----onSuccess!!!");
                    for (int i = 0; i < mMusicTagList.getTagList().size(); i++) {
                        Log.e(TAG, "mMusicTagList.getTagList().get(" + i + ")=" + mMusicTagList.getTagList().get(i));
                    }
                    break;
                case SearchAlbumData:
                    mSearchAlbumList = (SearchAlbumList) msg.obj;
                    Log.e(TAG,"-----关键字搜索的返回专辑列表个数="+mSearchAlbumList.getAlbums().size());
                    break;
                case SearchDataError:
                    Toast.makeText(CloudMusicActivity.this,"为获取到相关搜索内容,稍后再试!",Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //解决fragment 重叠的问题
        fragmentManager = getSupportFragmentManager();
        if(savedInstanceState !=null){
            personalRecommendFragment = (PersonalRecommendFragment) fragmentManager.findFragmentByTag("personalRecommendFragment_tag");
            recommandSongsFragment = (RecommandSongsFragment) fragmentManager.findFragmentByTag("recommandSongsFragment_tag");
            newSongsRankFragment = (NewSongsRankFragment) fragmentManager.findFragmentByTag("newSongRankFragment_tag");
        }

        super.onCreate(savedInstanceState);
        MusicApplication.changeTheme(this);
        setContentView(R.layout.activity_cloud_music);
        ButterKnife.bind(this);     //注解
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

//        choicePopular.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
//        choicePopular.getPaint().setAntiAlias(true);//抗锯齿
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        sharedPreferences = getSharedPreferences("userStyle", Context.MODE_PRIVATE);
        boolean flag = sharedPreferences.getBoolean("isNigtht", false);
        toolbar.setNavigationIcon(R.mipmap.action_back_normal);

        initView();

        //初始化喜马拉雅SDK
        initXiMaLaYaSDK();

        if (OkHttpUtils.isNetworkAvailable(mContext)) {
            Log.e(TAG, "------网络已经连接-----");
            //获取喜马拉雅数据的分类(资讯,音乐,有声书,娱乐,等等),音乐Category id =2;可以直接获取音乐
            getMusic_Data();


        } else {
            Toast.makeText(CloudMusicActivity.this, "hi,没有网络哦,请检查网络", Toast.LENGTH_SHORT).show();
        }
    }

    private void getMusic_Data() {

    }

    private void initXiMaLaYaSDK() {

        mContext = CloudMusicActivity.this;
        mFinalBitmap = FinalBitmap.create(mContext.getApplicationContext());
        mFinalBitmap.configLoadingImage(R.mipmap.ic_launcher);
        mFinalBitmap.configLoadfailImage(R.mipmap.ic_launcher);
        mFinalHttp = new FinalHttp();
        //初始化接口
        mXimalaya = CommonRequest.getInstanse();
        mXimalaya.init(mContext, mAppSecret);
        mXimalaya.setDefaultPagesize(50);
        mPlayerManager = XmPlayerManager.getInstance(mContext);//获取内容发到管理器
        mPlayerManager.init();
        mPlayerManager.getPlayerStatus();
    }


    private void initView() {
        Utils.setColor(this, getResources().getColor(R.color.hotpink));    //设置状态栏颜色
        recommendationId.setTypeface(MusicApplication.typeface);
        recommendSongsId.setTypeface(MusicApplication.typeface);
        newSongListId.setTypeface(MusicApplication.typeface);


        showFragment(FRAGMENT_ONE);


        search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                   String  tv_search = search.getText().toString();

                    getSearchAlbumData(tv_search);// 搜索框 输入框访问喜马拉雅

                }
                return true;
            }
        });
    }

    private void getSearchAlbumData(String tv_search) {
        Map<String, String> map = new HashMap<String, String>();
        map.put(DTransferConstants.SEARCH_KEY, tv_search);
        map.put(DTransferConstants.CATEGORY_ID, "");
        map.put(DTransferConstants.PAGE, ""+1);
        CommonRequest.getSearchedAlbums(map, new IDataCallBack<SearchAlbumList>() {
            @Override
            public void onSuccess(SearchAlbumList searchAlbumList) {

                Log.e(TAG, "Search数据长度--onSuccess " + (searchAlbumList != null));

                if (searchAlbumList != null && searchAlbumList.getAlbums() != null && searchAlbumList.getAlbums().size() != 0) {


                    Log.e(TAG, "Search测试3----------");
                    Message msg = new Message();
                    msg.what = SearchAlbumData;
                    msg.obj = searchAlbumList;
                    mHandler.sendMessage(msg);


                }
            }

            public void onError(int i, String s) {

                Log.e(TAG, "Search数据长度--onError " + i + ", " + s);
                Message msg = new Message();
                msg.what = SearchDataError;
                mHandler.sendMessage(msg);


        }
        });


    }

    @OnClick({R.id.toolbar,R.id.details,R.id.recommendation_id, R.id.recommend_songs_id, R.id.new_song_list_id, R.id.test})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar:
                //隐藏软键盘
                InputMethodManager imm3 = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                imm3.hideSoftInputFromWindow(view.getWindowToken(), 0);
                break;
            case R.id.details:
                InputMethodManager imm2 = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                imm2.hideSoftInputFromWindow(view.getWindowToken(), 0);
                break;
            case R.id.recommendation_id:
                showFragment(FRAGMENT_ONE);
                break;
            case R.id.recommend_songs_id:
                showFragment(FRAGMENT_TWO);
                break;
            case R.id.new_song_list_id:
                showFragment(FRAGMENT_THREE);
                break;
            //测试昼夜模式
            case R.id.test:
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        if (MusicApplication.isChange) {
                            Log.e(TAG, "白天模式" + MusicApplication.isChange);
                            flag_dn = MusicApplication.isChange = false;
                            Log.e(TAG, "白天模式flag:::" + flag_dn);
                        } else {
                            Log.e(TAG, "夜间模式" + MusicApplication.isChange);
                            flag_dn = MusicApplication.isChange = true;
                            Log.e(TAG, "夜间模式flag::::" + flag_dn);
                        }
                        editor.putBoolean("isNigtht", flag_dn);
                        editor.commit();
                        CloudMusicActivity.this.startActivity(new Intent(CloudMusicActivity.this, CloudMusicActivity.class));
                        //CloudMusicActivity.this.recreate();
                        finish();
                    }
                }, 0);
                break;
        }
    }

    private void showFragment(int index) {
        FragmentTransaction transactions = fragmentManager.beginTransaction();
        hideFragment(transactions);
        boolean dnflag = sharedPreferences.getBoolean("isNigtht", false);
        switch (index) {
            case FRAGMENT_ONE:
                if (personalRecommendFragment == null) {

                    personalRecommendFragment = new PersonalRecommendFragment();
                    transactions.add(R.id.details, personalRecommendFragment,"personalRecommendFragment_tag");
                } else {
                    transactions.show(personalRecommendFragment);
                }
                if (dnflag) {
                    recommendationId.setTextColor(getResources().getColor(R.color.md_pink_300));
                    recommendSongsId.setTextColor(getResources().getColor(R.color.md_white_1000));
                    newSongListId.setTextColor(getResources().getColor(R.color.md_white_1000));
                } else {
                    recommendationId.setTextColor(getResources().getColor(R.color.md_green_500));
                    recommendSongsId.setTextColor(getResources().getColor(R.color.md_black_1000));
                    newSongListId.setTextColor(getResources().getColor(R.color.md_black_1000));

                }
                recommendFirstImv.setImageResource(R.mipmap.research_development_icon_green);
                recommendSecondImv.setImageResource(R.mipmap.recommend_songs_icon_gray);
                recommendThirdImv.setImageResource(R.mipmap.new_song_list_icon_gray);

                break;
            case FRAGMENT_TWO:
                if (recommandSongsFragment == null) {
                    recommandSongsFragment = new RecommandSongsFragment();
                    transactions.add(R.id.details, recommandSongsFragment,"recommandSongsFragment_tag");
                } else {
                    transactions.show(recommandSongsFragment);
                }
                if (dnflag) {
                    recommendationId.setTextColor(getResources().getColor(R.color.md_white_1000));
                    recommendSongsId.setTextColor(getResources().getColor(R.color.md_pink_300));
                    newSongListId.setTextColor(getResources().getColor(R.color.md_white_1000));
                } else {
                    recommendationId.setTextColor(getResources().getColor(R.color.md_black_1000));
                    recommendSongsId.setTextColor(getResources().getColor(R.color.md_green_500));
                    newSongListId.setTextColor(getResources().getColor(R.color.md_black_1000));

                }

                recommendFirstImv.setImageResource(R.mipmap.research_development_icon_gray);
                recommendSecondImv.setImageResource(R.mipmap.recommend_songs_icon_green);
                recommendThirdImv.setImageResource(R.mipmap.new_song_list_icon_gray);
                break;
            case FRAGMENT_THREE:
                if (newSongsRankFragment == null) {
                    newSongsRankFragment = new NewSongsRankFragment();
                    transactions.add(R.id.details, newSongsRankFragment,"newSongRankFragment_tag");
                } else {
                    transactions.show(newSongsRankFragment);
                }
                if (dnflag) {
                    recommendationId.setTextColor(getResources().getColor(R.color.md_white_1000));
                    recommendSongsId.setTextColor(getResources().getColor(R.color.md_white_1000));
                    newSongListId.setTextColor(getResources().getColor(R.color.md_pink_300));
                } else {
                    recommendationId.setTextColor(getResources().getColor(R.color.md_black_1000));
                    recommendSongsId.setTextColor(getResources().getColor(R.color.md_black_1000));
                    newSongListId.setTextColor(getResources().getColor(R.color.md_green_500));

                }
                recommendFirstImv.setImageResource(R.mipmap.research_development_icon_gray);
                recommendSecondImv.setImageResource(R.mipmap.recommend_songs_icon_gray);
                recommendThirdImv.setImageResource(R.mipmap.new_song_list_icon_green);
                break;
        }
        transactions.commit();
    }

    private void hideFragment(FragmentTransaction transactions) {

        if (personalRecommendFragment != null) {
            transactions.hide(personalRecommendFragment);
        }
        if (recommandSongsFragment != null) {
            transactions.hide(recommandSongsFragment);
        }
        if (newSongsRankFragment != null) {
            transactions.hide(newSongsRankFragment);
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent mIntent = new Intent(this, MainActivity.class);
                //mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(mIntent);
                finish();
                break;

            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent mIntent = new Intent(this, MainActivity.class);
        //mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(mIntent);
        finish();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值