开发者

setBackgroundResource of TextView in listitem

开发者 https://www.devze.com 2023-03-07 12:25 出处:网络
I\'ve got an activity that presents a listview of tracks of songs. When an item is clicked, it streams the appropriate media file. I have a textview in each row that displays the length of the track.

I've got an activity that presents a listview of tracks of songs. When an item is clicked, it streams the appropriate media file. I have a textview in each row that displays the length of the track. When the track is playing, I switch the backgroundresource of the textview in the row to a pause button drawable. In other words, when it's ready to play, it displays a play button and when its currently playing it displays a pause button. Simple enough....

Currently, I'm doing something like this to set the drawable to pause button if the mediaplayer is playing:

if(mp.isPlaying()) { _player.setBackgroundResource(R.drawable.pausebtn); _player.setText(" :" + String.valueOf(mp.getDuration()/1000));

I'm doing this in my Runnable which has the mediaplayer callback of onPrepared.

Problem is that I need the drawable to be set in THAT list item, i.e. the one which was clicked and whose track is being played. How can I grab hold of which one was clicked and set ITS textview to the new drawable?

Here's the full code:

package com.me.player

import java.net.URL;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.mtv.datahandler.Artist;
import com.mtv.datahandler.DataBaseHelper;
import com.mtv.datahandler.Track;
import com.mycompany.http.HttpRequest;


public class ArtistAudio extends ControllerActivity implements OnCompletionListener, OnPreparedListener, OnErrorListener{

    private int METHOD_TYPE = 0;
    private static final int GET_AUDIO = 1;

    int CURRENT_POSITION = 0;
    int DURATION = 0;

    public static final String AUDIO_FEED_URL = "http://direct.rhapsody.com/metadata/data/getTopTracksForArtist.xml?blabla";
    public static final int MAX_TRACKS = 200;
    ArrayList<Track> tracks = new ArrayList<Track>();
    Artist artist;

    private MediaPlayer mp;
    private int mSongPlaying = 0;
    TextView _player;

    @Override
    protected void progressRunnableComplete() {
        if(isFinishing()){
            return;
        }
        if(METHOD_TYPE == GET_AUDIO){
            setList();
        }
    }

    public void setList(){
        ListView listview = (ListView)findViewById(R.id.ListView01);
        //      ListView listview = (ListView)findViewById(R.id.ListView01);
        if(listview == null){
            setContent(R.layout.artistaudio);
            listview = (ListView)findViewById(R.id.ListView01);
        }

        //      listview.addHeaderView();
        listview.setCacheColorHint(0);
        listview.setAdapter(new TrackListAdapter());
        listview.setSelector(R.drawable.listbackground);
        listview.setDividerHeight(1);
        listview.setDivider(getResources().getDrawable(R.drawable.img_dotted_line_horz));
        listview.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                TrackClicked(arg2);
            }
        });
    }

    public void TrackClicked(int arg2){



        mSongPlaying = arg2;


        Track track = tracks.get(arg2);
        String url = track.requestInfo("previewURL");

        mHandler.post(new PlaySong(url));









//      mHandler.post(new PlaySong("http://dc237.4shared.com/img/315443275/33f14ef2/dlink__2Fdownload_2F9y5VGjVt_3Ftsid_3D20100705-131850-40aa0b87/preview.mp3"));
    }

    public void setDuration(int n) {
        DURATION = n;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Audio Clips");
        setContent(R.layout.artistaudio);

        Object o = getIntent().getParcelableExtra("artist");
        if(o!=null){
            artist = (Artist)o;
        }

        progressRunnable(new Runnable(){
            public void run(){
                getTracks();
            }
        }, "Loading. Please Wait...",false);


    }

    protected void getTracks() {
        METHOD_TYPE = GET_AUDIO;
        if(!DataBaseHelper.isOnline(this)){
            RUNNABLE_STATE = RUNNABLE_FAILED;
            return;
        }
        HttpRequest req;
        try {
            req = new HttpRequest(new URL(AUDIO_FEED_URL+artist.requestInfo("rhapsodyID")));
            Document doc = req.AutoXMLNoWrite();
            NodeList items = doc.getElementsByTagName("e");
            tracks= new ArrayList<Track>();
            for(int i=0; i<items.getLength(); i++){
                Track newsitem = new Track(items.item(i));
                tracks.add(newsitem);   
            }
            RUNNABLE_STATE = RUNNABLE_SUCCESS;
        } catch (Throwable e) {
            RUNNABLE_STATE = RUNNABLE_FAILED;
            e.printStackTrace();
        }   
    }

    public void onPause(){
        super.onPause();
        try{mp.stop();}catch(Exception e){e.printStackTrace();}
        try{mp.reset();}catch(Exception e){e.printStackTrace();}
        try{mp.release();}catch(Exception e){e.printStackTrace();}
        mp = null;

    }

    private class TrackListAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return tracks.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return tracks.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            AudioCell blogView = null;
            if (convertView != null) {
                if(convertView.getClass() == TextView.class){
                    convertView = null;
                }
            }
            if (convertView == null) {
                blogView = new AudioCell(parent.getContext());
            }
            else {
                blogView = (AudioCell) convertView;
            }
            blogView.display(position);
            return blogView;
        }
    } 

    /** this class is responsible for rendering the data in the model, given the selection state */
    class AudioCell extends RelativeLayout {

        TextView _title;



        int currentPosition;



        public AudioCell(Context mContext) {
            super(mContext);
            _createUI(mContext);
        }

        /** create the ui components */
        private void _createUI(Context m) {


            RelativeLayout.LayoutParams params;
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

            _player = new TextView(m);
            _player.setId(2);
            _player.setBackgroundResource(R.drawable.playbtn);
            _player.setText(":30");





            addView(_player);
            params.addRule(RelativeLayout.CENTER_VERTICAL,1);
            _player.setLayoutParams(params);


            _title = new TextView(m);
            _title.setTextColor(Color.BLACK);       
            params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));
            params.addRule(RelativeLayout.CENTER_VERTICAL,1);
            params.addRule(RelativeLayout.RIGHT_OF, _player.getId());

            params.setMargins(0, 10, 0, 10);
            _title.setGravity(Gravity.CENTER_VERTICAL);
            _title.setLayoutParams(params);
            _title.setId(102);
            addView(_title);
            params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));

//          _player.setOnClickListener(new View.OnClickListener() {
//              
//              @Override
//              public void onClick(Vi开发者_JAVA百科ew v) {
//                  PlaySong.PlaySong("http://http://www.noiseaddicts.com/samples/2544.mp3");
//                  
//              }
//          });
//          














        }

        /** update the views with the data corresponding to selection index */
        public void display(int index) {
            _title.setText(tracks.get(index).requestInfo("name"));
        }
    }

    private class PlaySong implements Runnable{
        String songURL;

        public PlaySong(String url){
            songURL = url;
        }

        public void run(){
            try{mp.stop();}catch(Exception e){e.printStackTrace();}


            try{mp.reset();}catch(Exception e){e.printStackTrace();}

            if(mp==null){
                createPlayer();
            }
            try{mp.reset();}catch(Exception e){e.printStackTrace();}
            try{mp.setAudioStreamType(AudioManager.STREAM_MUSIC);}catch(Exception e){e.printStackTrace();}
            try{mp.setDataSource(songURL);}catch(Exception e){e.printStackTrace();}
            try{mp.prepareAsync();}catch(Exception e){e.printStackTrace();}



        }
    }

    public void createPlayer(){
        mp = new MediaPlayer();
        mp.setOnCompletionListener(this);
        mp.setOnPreparedListener(this);
        mp.setOnErrorListener(this);
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub
        try{mp.reset();}catch(Exception e){e.printStackTrace();}
//      if(mSongPlaying<tracks.size()-1)
//      {
//          TrackClicked(mSongPlaying+1);
//      }



        _player.setBackgroundResource(R.drawable.playbtn);

    }

    @Override
    public void onPrepared(MediaPlayer inMP) {
        // TODO Auto-generated method stub



        mp.start();
        if(mp.isPlaying()) {
            _player.setBackgroundResource(R.drawable.pausebtn);
            _player.setText(" :" + String.valueOf(mp.getDuration()/1000));


        }

    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // TODO Auto-generated method stub
        return false;
    }
}   

As you can see, my inner class AudioCell which extends RelativeLayout is what I'm using for the rows of my ListView....

Any thoughts? Where should I be setting the drawable and how can I make sure it does it only for the row that was clicked (i.e. for the track that's actually being played).


change the TrackClicked method's siggnature. pass both arg1 and arg3 from onItemClick and in the TrackClicked method do this arg1.setBackgroundResource(R.drawable.thebackground);


Inside your TrackClicked method, add this:

getAdapter().getChildAt(arg2).setBackgroundResource(R.drawable.thebackground);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号