Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android開發本地及網絡Mp3音樂播放器(十二)創建NetMusicListAdapter、SearchResult顯示網絡音樂列表

Android開發本地及網絡Mp3音樂播放器(十二)創建NetMusicListAdapter、SearchResult顯示網絡音樂列表

編輯:關於Android編程

實現功能:
實現NetMusicListAdapter(網絡音樂列表適配器)
實現SearchResult(搜索音樂對象)
使用Jsoup組件請求網絡,並解析音樂數據,並,音樂數據加載到列表中
實現FooterView

實現效果如圖:

\

\

\


FooterView:

\


實現代碼如下:
NetMusicListFragment如下:
package com.iwanghang.drmplayer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.iwanghang.drmplayer.adapter.MyMusicListAdapter;
import com.iwanghang.drmplayer.adapter.NetMusicListAdapter;
import com.iwanghang.drmplayer.utils.AppUtils;
import com.iwanghang.drmplayer.utils.Constant;
import com.iwanghang.drmplayer.utils.SearchMusicUtils;
import com.iwanghang.drmplayer.vo.Mp3Info;
import com.iwanghang.drmplayer.vo.SearchResult;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

public class NetMusicListFragment extends Fragment implements OnItemClickListener,OnClickListener {

    private ListView listView_net_music;

    //private ArrayList mp3Infos;

    private LinearLayout load_layout;
    private LinearLayout ll_search_btn_container;
    private LinearLayout ll_search_container;
    private ImageButton ib_search_btn;
    private EditText et_search_content;

    private NetMusicListAdapter netMusicListAdapter;

    //存放 網絡音樂 的集合
    private ArrayList searchResults = new ArrayList();

    private int page = 1;//搜索音樂的頁碼

    private MainActivity mainActivity;

    //private boolean isPause = false;//歌曲播放中的暫停狀態

    private int position = 0;//當前播放的位置,提供給PlayActivity

    //onAttach(),當fragment被綁定到activity時被調用(Activity會被傳入.).
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //mainActivity = (MainActivity) context;
        mainActivity = (MainActivity) getActivity();
    }

    public static NetMusicListFragment newInstance() {
        NetMusicListFragment net = new NetMusicListFragment();
        return net;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //UI組件初始化
        View view = inflater.inflate(R.layout.net_music_list_layout,null);
        //item
        listView_net_music = (ListView) view.findViewById(R.id.listView_net_music);
        //findViewById
        load_layout = (LinearLayout) view.findViewById(R.id.load_layout);
        ll_search_btn_container = (LinearLayout) view.findViewById(R.id.ll_search_btn_container);
        ll_search_container = (LinearLayout) view.findViewById(R.id.ll_search_container);
        ib_search_btn = (ImageButton) view.findViewById(R.id.ib_search_btn);
        et_search_content = (EditText) view.findViewById(R.id.et_search_content);

        //Item點擊事件監聽
        listView_net_music.setOnItemClickListener(this);
        //按鈕點擊事件監聽
        ll_search_btn_container.setOnClickListener(this);
        ib_search_btn.setOnClickListener(this);
        loadNetData();//加載網絡音樂
        return view;
    }

    private void loadNetData() {
        load_layout.setVisibility(View.VISIBLE);
        //加載網絡音樂的異步任務
        new LoadNetDataTask().execute(Constant.BAIDU_URL + Constant.BAIDU_DAYHOT);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_search_btn_container:
                ll_search_btn_container.setVisibility(View.GONE);
                ll_search_container.setVisibility(View.VISIBLE);
                break;
            case R.id.ib_search_btn:
                //搜索事件
                searchMusic();
                break;
        }
    }

    //搜索音樂
    private void searchMusic() {
        //隱藏鍵盤
        AppUtils.hideInputMethod(et_search_content);
        ll_search_btn_container.setVisibility(View.VISIBLE);
        ll_search_container.setVisibility(View.GONE);
        //獲取輸入的文字
        String key = et_search_content.getText().toString();
        if (TextUtils.isEmpty(key)){//如果為空,則,Toast提示
            Toast.makeText(mainActivity,"請輸入歌手或歌詞",Toast.LENGTH_SHORT).show();
            return;
        }
        load_layout.setVisibility(View.VISIBLE);//加載layout效果.顯示
        //填充item 使用SearchMusicUtils搜索音樂工具類,並,使用觀察者設計模式,自己回調,自己監聽
        //SearchMusicUtils.
    }

    //加載網絡音樂的異步任務
    //Android1.5提供了 工具類 android.os.AsyncTask,它使創建異步任務變得更加簡單,不再需要編寫任務線程和Handler實例即可完成相同的任務。
    class LoadNetDataTask extends AsyncTask{
        //onPreExecute方法用於在執行後台任務前做一些UI操作
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            load_layout.setVisibility(View.VISIBLE);//加載layout.顯示
            listView_net_music.setVisibility(View.GONE);//item.隱藏
            searchResults.clear();//搜索結果.清理
        }

        //doInBackground方法內部執行後台任務,不可在此方法內修改UI
        @Override
        protected Integer doInBackground(String... params) {
            String url = params[0];
            try {
                //使用Jsoup組件請求網絡,並解析音樂數據
                Document doc = Jsoup.connect(url).userAgent(Constant.USER_AGENT).timeout(6*1000).get();
//半壺紗							
//劉珂矣        	
//千年一般若影視原聲							
//韓磊        	
                //從doc分析以上html代碼;把所有span標簽下song-title查找出來,存在songTitles集合中;即,歌名集合;
                //從doc分析以上html代碼;把所有span標簽下author_list查找出來,存在artists集合中;即,歌手集合;
                Elements songTitles = doc.select("span.song-title");
                Elements artists = doc.select("span.author_list");
                //System.out.println(artists);
                for (int i=0;i半壺紗<,半壺紗就是a鏈接的內容);即,最終的歌名;
                    Elements urls = songTitles.get(i).getElementsByTag("a");
                    //System.out.println("@urls : " + urls);
                    searchResult.setUrl(urls.get(0).attr("href"));//設置最終的url
                    searchResult.setMusicName(urls.get(0).text());//設置最終的歌名

                    //a鏈接,存在urls集合中;即,歌曲url集合;
                    Elements artistElements = artists.get(i).getElementsByTag("a");
                    //System.out.println("@artistElements : " + artistElements);
                    searchResult.setArtist(artistElements.get(0).text());//設置最終的歌手

                    searchResult.setAlbum("熱歌榜");//設置最終的專輯

                    System.out.println("@searchResult : " + searchResult);
                    searchResults.add(searchResult);//把最終的所有信息,添加到集合
                }
                System.out.println("@searchResults : " + searchResults);
                //System.out.println("@songTitles.size() : " + searchResults.size());
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
            return 1;
        }

        //onPostExecute方法用於在執行完後台任務後更新UI,顯示結果
        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            if (result==1){
                netMusicListAdapter = new NetMusicListAdapter(mainActivity,searchResults);
                //System.out.println(searchResults);
                listView_net_music.setAdapter(netMusicListAdapter);
                listView_net_music.addFooterView(LayoutInflater.from(mainActivity).inflate(R.layout.footviwe_layout,null));
            }
            load_layout.setVisibility(View.GONE);
            listView_net_music.setVisibility(View.VISIBLE);
        }
    }




    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {

    }
}

NetMusicListAdapter如下:
package com.iwanghang.drmplayer.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.iwanghang.drmplayer.R;
import com.iwanghang.drmplayer.utils.MediaUtils;
import com.iwanghang.drmplayer.vo.Mp3Info;
import com.iwanghang.drmplayer.vo.SearchResult;

import java.util.ArrayList;

/**
 * 自定義的音樂列表適配器(網絡)
 * 為了方便擴展,因為之前沒有考慮到顯示專輯封面
 * Created by iwanghang on 30/4/16.
 */
public class NetMusicListAdapter extends BaseAdapter{

    private Context ctx; //上下文對象引用
    private ArrayList searchResults;//存放SearchResult引用的集合
    private SearchResult searchResult;//SearchResult對象引用
    //private int pos = -1;			//列表位置

    /**
     * 構造函數
     * @param ctx    上下文
     * @param searchResults  集合對象
     */
    public NetMusicListAdapter(Context ctx, ArrayList searchResults){
        this.ctx = ctx;
        this.searchResults = searchResults;
        //System.out.println("MyMusicListAdapter.java #0 : ctx = " + ctx + ",mp3Infos = " + mp3Infos.size());
    }

    public ArrayList searchResults() {
        System.out.println("NetMusicListAdapter.java #1 : public ArrayList searchResults() {");
        return searchResults;
    }

    public void setSearchResults(ArrayList searchResults) {
        System.out.println("NetMusicListAdapter.java #2 : public void setMp3Infos(ArrayList searchResults) {");
        this.searchResults = searchResults;
    }


    @Override
    public int getCount() {
        //System.out.println("NetMusicListAdapter.java #3 : public int getCount() {" + mp3Infos.size());
        //return mp3Infos.size();
        return searchResults.size();
    }

    @Override
    public Object getItem(int position) {
        System.out.println("NetMusicListAdapter.java #4 : public Object getItem(int position) {");
        return searchResults.get(position);
    }

    @Override
    public long getItemId(int position) {
        //System.out.println("NetMusicListAdapter.java #5 : public long getItemId(int position) {");
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //System.out.println("NetMusicListAdapter.java #6 : public View getView ");
        ViewHolder vh;
        if(convertView==null){
            //vh = new ViewHolder();
            convertView = LayoutInflater.from(ctx).inflate(R.layout.item_net_music_list,null);
            vh = new ViewHolder();
            vh.textView1_title = (TextView) convertView.findViewById(R.id.textView1_title);
            vh.textView2_singer = (TextView) convertView.findViewById(R.id.textView2_singer);
            //vh.textView3_time = (TextView) convertView.findViewById(R.id.textView3_time);
            //vh.imageView1_ablum = (ImageView) convertView.findViewById(R.id.imageView1_ablum);

            //System.out.println("NetMusicListAdapter.java #7 : textView1_title = " + vh.textView1_title);
            convertView.setTag(vh);//表示給View添加一個格外的數據,
        }else {
            vh = (ViewHolder)convertView.getTag();//通過getTag的方法將數據取出來
        }

        SearchResult searchResult = searchResults.get(position);
        vh.textView1_title.setText(searchResult.getMusicName());//顯示標題
        vh.textView2_singer.setText(searchResult.getArtist());//顯示歌手
        //vh.textView3_time.setText(MediaUtils.formatTime(mp3Info.getDuration()));//顯示時長

        //獲取專輯封面圖片
        //Bitmap albumBitmapItem = MediaUtils.getArtwork(ctx,mp3Info.getId(),mp3Info.getAlbumId(),true,true);
        //System.out.println("NetMusicListAdapter.java #8 : albumBitmapItem = " + albumBitmapItem.getConfig());

        //改變播放界面專輯封面圖片
        //vh.imageView1_ablum.setImageBitmap(albumBitmapItem);
        //vh.imageView1_ablum.setImageResource(R.mipmap.music);

        return convertView;
    }

    /**
     * 定義一個內部類
     * 聲明相應的控件引用
     */
    static class ViewHolder{
        //所有控件對象引用
        TextView textView1_title;//標題
        TextView textView2_singer;//歌手
        //TextView textView3_time;//時長
        //ImageView imageView1_ablum;//專輯封面圖片
    }
}

SearchResult如下:
package com.iwanghang.drmplayer.vo;

/**
 * Created by iwanghang on 16/4/29.
 * 搜索音樂的對象
 */
public class SearchResult {
    private String musicName;
    private String url;
    private String artist;
    private String album;
    private long size;//大小


    //set方法,get方法
    public String getMusicName() {
        return musicName;
    }

    public void setMusicName(String musicName) {
        this.musicName = musicName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public String getAlbum() {
        return album;
    }

    public void setAlbum(String album) {
        this.album = album;
    }

    public long getSize() {
        return size;
    }

    public void setSize(long size) {
        this.size = size;
    }

    @Override
    public String toString() {
        return "SearchResult{" +
                "musicName='" + musicName + '\'' +
                ", url='" + url + '\'' +
                ", artist='" + artist + '\'' +
                ", album='" + album + '\'' +
                ", size=" + size +
                '}';
    }
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved