gridview与adapter使用实例

1、activity

public class RecordActivity extends BaseActivity implements OnClickListener {

private Context mContext;
List<View> viewList = new ArrayList<View>();
private GridView gridview_story;
private ImageButton iv_custom;
private RecordGridViewAdapter adapter;
private List<Music> musics;


private CheckBox mCbMusicStatus ; //播放 暂停按钮

private ImageView mIvMusicStatusBack ; //左边返回按钮

private ImageView mIvMusicStatusAlbum ;//当前播放歌曲的图片

private TextView mTvMusicStatusName ;//当前播放歌曲名

private View mViewMusicStatus ;

private BgMusicControlService msgService;

private MusicManager mMusicManager ;



private boolean forward = false;//用来标记onstop被调用的时候是返回还是跳转到其他activity 是跳转则暂停播放音乐
private boolean playing; // 用来标记跳转前是播放还是暂停状态 是播放就恢复播放

ServiceConnection conn = new ServiceConnection() {


@Override
public void onServiceDisconnected(ComponentName name) {


}


@Override
public void onServiceConnected(ComponentName name, IBinder service) {
msgService = ((BgMusicControlService.MsgBinder) service).getService();


msgService.setmIMusic(new IMusic() {


@Override
public void getMusicItemList(List<Music> musicList, int position) {
}


@Override
public void getMusicTitleAndDuration(Music music, long duration,int playMode) {
mTvMusicStatusName.setText(music.getMname());
getAlblum(music);
}


@Override
public void updateMusicStatus(long currentTime) {
}
});
}
};

private void getAlblum(Music music) {
String url = CommConst.SIT_ROOT_FILE_URL + music.getCoverpic();
mIvMusicStatusAlbum.setTag(url);
AsyncImageDownloader.getInstance(mContext).imageDownload(url, mIvMusicStatusAlbum,
CommConst.ROOT_PIC_PATH, new OnImageDownload() {
@Override
public void onDownloadSucc(Bitmap bitmap, String c_url,
ImageView imageView) {
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
imageView.setTag(null);
}
}
});
}




private Handler handler = new Handler() {


@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1000:
adapter = new RecordGridViewAdapter(RecordActivity.this, musics);
gridview_story.setAdapter(adapter);
break;
default:
break;
}
}


};

@Override
protected void onResume() {
super.onResume();
Intent intent = new Intent(mContext, BgMusicControlService.class);
boolean flag = getApplicationContext().bindService(intent, conn, Context.BIND_AUTO_CREATE);
//Log.e("liujw","################### bindservice "+ flag);

mCbMusicStatus.setChecked(!playing);
Log.d("zhengchuanshu", "onResume"  + BgMusicControlService.getPlayerStatus());
}

@Override
protected void onRestart() {
super.onRestart();
if(playing)
mMusicManager.resumeMusic();
Log.d("zhengchuanshu", "onRestart" + BgMusicControlService.getPlayerStatus());
}

@Override
protected void onPause() {
super.onPause();
}

@Override
protected void onStop() {
super.onStop();
playing = BgMusicControlService.getPlayerStatus();
if(forward && playing)
mMusicManager.pauseMusic();
forward = false;//重置状态 否则一次设置为true 返回的时候也是true
getApplicationContext().unbindService(conn);
}

@Override
protected void onDestroy() {
super.onDestroy();
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.record_activity);
mContext = this;
mMusicManager = MusicManager.getInstance(mContext);
init();
initMusicPanelView();
requestWebService();
}

private void requestWebService(){
WebRequest.requestFromWeb(new AsyncHttpResponseHandler() {


@Override
public void onSuccess(int statusCode, Header[] arg1,
byte[] responseBody) {
if (statusCode == 200) {
String result = new String(responseBody);
musics = RecordDas.getMusicFromWeb(result);
handler.sendEmptyMessage(1000);
}
}


@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable erro) {
System.out.println(erro.toString());


}
}, CommConst.REQUEST_MUSICLIST_METHOD, new String[][] {{"lang", App.getCountryCode()}});
}


private void init() {
gridview_story = (GridView) findViewById(R.id.gridview_story);
iv_custom = (ImageButton) findViewById(R.id.iv_custom);
iv_custom.setOnClickListener(this);
gridview_story.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Music music = musics.get(position);
if(music.getDownloaded() == 3){
forward = true;

Intent intent = new Intent();
Bundle bundle = new Bundle();
// bundle.putString("mp3", CommConst.RECORD_FILE_PATH + music.getMname()+".mp3");
bundle.putString("lrc", CommConst.RECORD_FILE_PATH + music.getMname()+".lrc");
bundle.putString("pic", CommConst.SIT_ROOT_FILE_URL + music.getCoverpic());
bundle.putString("Name", music.getMname());
intent.setClass(mContext, RecordPlayActivity.class); 
intent.putExtras( bundle);
mContext.startActivity(intent);
}else{
adapter.downloadMusicAndLyric(music);
}
}
});
}

/**
* 初始化下面的框view
*/
private void initMusicPanelView() {
mViewMusicStatus = (View)findViewById(R.id.include_music_status);
mCbMusicStatus = (CheckBox)mViewMusicStatus.findViewById(R.id.cb_music_status);
mIvMusicStatusBack = (ImageView)mViewMusicStatus.findViewById(R.id.iv_music_status_icon);
mIvMusicStatusAlbum = (ImageView)mViewMusicStatus.findViewById(R.id.iv_alblum);
mTvMusicStatusName = (TextView)mViewMusicStatus.findViewById(R.id.tv_name);
mIvMusicStatusBack.setImageResource(R.drawable.ic_music_back_selector);
mIvMusicStatusBack.setOnClickListener(this);

mViewMusicStatus.setOnClickListener(this);
mCbMusicStatus.setOnClickListener(this);

mMusicManager = MusicManager.getInstance(mContext);


playing = BgMusicControlService.getPlayerStatus();

}


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_music_status_icon:
finish();
break;
case R.id.cb_music_status :
mMusicManager.changeMusicStauts();
break ;
case R.id.include_music_status:
Intent iMusic = new Intent(this, MusicPlayerActivity.class);
startActivity(iMusic);
break;
case R.id.iv_custom:
forward = true;
Intent intent = new Intent(RecordActivity.this, RecordCustomActivity.class);
startActivity(intent);
break;
default:
break;
}
}

}


2、Adapter


public class RecordGridViewAdapter extends BaseAdapter {
private Context mContext;
private List<Music> musics;
private LayoutInflater layoutInflater;
private RecordActivity r;
// 下载管理类
private IwitDownloadManager manager;
//我的内容观察者
private MyContentObserver mMyContentObserver;
//
public String mp3Path;
public String lrcPath;
String names;
private Handler handler = new Handler(){


@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch(msg.what){
case 1000:
notifyDataSetChanged();
break;
}
}

};

private OnContentListener mOnContentListener = new OnContentListener() {

@Override
public void onChange(List<DownloadInfoBean> listDownloadInfoBean) {
// TODO Auto-generated method stub
scanDownloadInfoBean(listDownloadInfoBean);
//显示
handler.sendEmptyMessage(1000);
}
};
public int getProgressValue(long total_size, long current_size) {
int progress = 0;
progress = (int) (current_size * 100 / total_size);
return progress;
}
private void scanDownloadInfoBean(List<DownloadInfoBean> listDownloadInfoBean){
String url;
int status;
int total_size;
int current_size;
int progress;
long downloadId;
for(DownloadInfoBean downloadbean : listDownloadInfoBean){
url = downloadbean.getDownload_uri();
status = downloadbean.getDownload_status();
total_size = downloadbean.getDownload_total_bytes();
current_size = downloadbean.getDownload_current_bytes();
progress = getProgressValue(total_size,current_size);
downloadId = downloadbean.getDownload_id();
for(Music music : musics){
//根据下载的url和歌词文件全路径来判断是不是下载了
if(url.equals( CommConst.SIT_ROOT_FILE_URL + music.getLyric())){
music.setStatus(status);
music.setProgress(progress);
music.setDownloadId(downloadId);
}
}
}
}

 
public RecordGridViewAdapter(Context c, List<Music> musics) {
mContext = c;
this.musics = musics;
 
manager = IwitDownloadManager.getInstance(c);
mMyContentObserver = new MyContentObserver(c, manager, mOnContentListener);
scanDownloadInfoBean(manager.queryDownloadInfoByPackageName(mContext.getPackageName()));
App.ctx.getContentResolver().registerContentObserver(Downloads.Impl.CONTENT_URI, true, mMyContentObserver);

}


public int getCount() {
// Log.v("qh", "Lmusic:"+musics.size());
return musics == null ? 0 : musics.size();
}


// 获取图片在库中的位置
public Object getItem(int position) {
return musics.get(position);
}


// 获取图片ID
public long getItemId(int position) {
return position;
}


public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
ViewHolder holder;


if (convertView == null) {
layoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(
R.layout.record_fragment_story_refresh_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}


final Music music = musics.get(position);
Log.v("qh", "music:" + musics.size());
holder.img.setImageResource(R.drawable.menu_ic_default);
String url = CommConst.SIT_ROOT_FILE_URL + music.getCoverpic();
holder.img.setTag(url);
String name = music.getMname();
holder.mTvName.setText(name);


// 异步加载书籍图片封面
AsyncImageDownloader.getInstance(mContext).imageDownload(url,
holder.img, CommConst.ROOT_PIC_PATH, new OnImageDownload() {
@Override
public void onDownloadSucc(Bitmap bitmap, String c_url,
ImageView imageView) {
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
});


/* holder.img.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {

}
});
holder.progressBar.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
downloadMusicAndLyric(music);
}
});*/
 

holder.progressBar.setProgress(music.getProgress());

  if (music.getStatus() == CommConst.STATUS_DOWNLOADING) {
  music.setDownloaded(1);
  //holder.mTvName.setText(mContext.getResources().getString(R.string.music_downloading));
  // 1 表示正在下载
  } else if (music.getStatus() == CommConst.STATUS_READY) {
  music.setDownloaded(3);
//holder.mTvName.setText(mContext.getResources().getString(R.string.music_read));
holder.progressBar.setProgress(100);
  } else if (music.getStatus() == CommConst.STATUS_PAUSE) {
  music.setDownloaded(2);
  //holder.mTvName.setText(mContext.getResources().getString(R.string.music_pause));
  } else if (music.getStatus() >= CommConst.STATUS_MOUNT_BEGIN
  && music.getStatus() <= CommConst.STATUS_MOUNT_END) {
  //holder. mTvName.setText(mContext.getResources().getString(R.string.music_pause));
  // 这里的2 表示挂载,该状态与暂停基本类似
  music.setDownloaded(2);
} else if (music.getStatus() == 0) {
music.setDownloaded(0);
} else {
// 0 表示音乐未下载
music.setDownloaded(0);
}
return convertView;


}



public void downloadMusicAndLyric(final Music music) {
// 点击下载MP3
String url_mp3 = CommConst.SIT_ROOT_FILE_URL + music.getMfname();
String url_file = CommConst.SIT_ROOT_FILE_URL + music.getLyric();

int count = manager.getDownloadingCount(CommConst.PACKAGE_NAME);
Log.v("qh", "music.getMfname()::"+music.getMfname());
Log.v("qh", "music.getLyric()::"+music.getLyric());
 
 
                 if(NetWorkTools.getAPNType(mContext) == -1){
                Toast.makeText(mContext,mContext.getString(R.string.write_no_net), 1).show(); 
                 }else{     
                    if(count <= 3){  
                    if( music.getDownloaded() == null || music.getDownloaded() == 0){
                    if(music.getDownloadId() == 0){
                    Logger.v("qh", " music.getMfname()::"+ music.getMfname());
                    Logger.v("qh", " music.getLyric()::"+ music.getLyric());
                   
                    String mp3Name= music.getMname()+".mp3";
                    String  lrcName= music.getMname()+".lrc";
                    names = music.getMname();
                    //long mp3_id = manager.startDownload(url_mp3, mp3Name, CommConst.RECORD_FILE_PATH);
                    long file_id = manager.startDownload(url_file, lrcName, CommConst.RECORD_FILE_PATH);
                    mp3Path = CommConst.RECORD_FILE_PATH + mp3Name;
                    lrcPath = CommConst.RECORD_FILE_PATH + lrcName;
                     
                    music.setDownloadId(file_id);
                    } else{
                    manager.resumeDownload(music.getDownloadId());
                    }
                    }else if (music.getDownloaded() == 1) {
                    manager.pauseDownload(music.getDownloadId());
  } else if (music.getDownloaded() == 2) {
  manager.resumeDownload(music.getDownloadId());
 
                    }else{
                    Toast.makeText(mContext,mContext.getString(R.string.write_download_too_much),1).show();
   
                    }
                 }
}


class ViewHolder {
private ImageView img;
private TextView mTvName;
private CustomProgressBar progressBar; 
public ViewHolder(View convertView){
mTvName = (TextView) convertView.findViewById(R.id.item_text);
img = (ImageView) convertView.findViewById(R.id.item_image);
progressBar = (CustomProgressBar) convertView.findViewById(R.id.progressbar_download);
}
}
 

}


3、item布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:android_custom="http://schemas.android.com/apk/res/com.iwit.ds"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants"
    android:paddingBottom="4dp" >


    
    <RelativeLayout 
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content">
   
   <com.iwit.ds.ui.view.RoundImageView
       android:id="@+id/item_image"
       android:layout_width="80dp"
       android:layout_height="80dp"
       android:layout_centerHorizontal="true"
       android:scaleType="centerCrop" >
   </com.iwit.ds.ui.view.RoundImageView>
   
   <com.iwit.ds.ui.view.CustomProgressBar 
      android:id="@+id/progressbar_download"
      android:layout_width="80dp"
       android:layout_height="80dp"
       android:layout_centerHorizontal="true"
       android:scaleType="centerCrop"  />
   
    </RelativeLayout>


    <com.iwit.ds.ui.view.TextviewRolling
        android:id="@+id/item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/image"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dp"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:singleLine="true"
        android:textColor="#33a3dc" />
<!-- 
    <ProgressBar
        android:id="@+id/progressbar_download"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:layout_below="@+id/item_text"
        android:layout_centerHorizontal="true"
        android:max="100" />
 -->
</RelativeLayout>


4、item自定义控件

(1)

public class RoundImageView extends ImageView {
 
    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
 
    public RoundImageView(Context context) {
        super(context);
        init();
    }
 
    private final RectF roundRect = new RectF();
    private float rect_adius = 12;
    private final Paint maskPaint = new Paint();
    private final Paint zonePaint = new Paint();
 
    private void init() {
        maskPaint.setAntiAlias(true);
        maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //
        zonePaint.setAntiAlias(true);
        zonePaint.setColor(Color.WHITE);
        //
        float density = getResources().getDisplayMetrics().density;
        rect_adius = rect_adius * density;
    }
 
    public void setRectAdius(float adius) {
        rect_adius = adius;
        invalidate();
    }
 
    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
            int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        int w = getWidth();
        int h = getHeight();
        roundRect.set(0, 0, w, h);
    }
 
    @Override
    public void draw(Canvas canvas) {
        canvas.saveLayer(roundRect, zonePaint, Canvas.ALL_SAVE_FLAG);
        canvas.drawRoundRect(roundRect, rect_adius, rect_adius, zonePaint);
        //
        canvas.saveLayer(roundRect, maskPaint, Canvas.ALL_SAVE_FLAG);
        super.draw(canvas);
        canvas.restore();
    }
 
}

(2)

public class CustomProgressBar extends View {
private Paint paint;
private int max; //最大进度 默认100
private int progress; //当前进度 默认0
private Rect rect;

private int color; //背景颜色 默认#64f173ac赤紫


public CustomProgressBar(Context context) {
this(context,null);
}

public CustomProgressBar(Context context, AttributeSet attrs) {
this(context,attrs,0);
}

public CustomProgressBar(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint();

TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomProgressBar);

max = mTypedArray.getInteger(R.styleable.CustomProgressBar_max, 100);
progress = mTypedArray.getInteger(R.styleable.CustomProgressBar_progress, 0);
color = mTypedArray.getColor(R.styleable.CustomProgressBar_backgroud, Color.parseColor("#78f173ac"));
paint.setColor(color);
mTypedArray.recycle();
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int top = getHeight() * progress / 100;
rect = new Rect(getLeft(),getTop() + top,getRight(),getBottom());
canvas.drawRect(rect, paint);
}

public int getProgress() {
return progress;
}


public void setProgress(int progress) {
if(progress < 0)
progress = 0; //当网络获取字节总数失败时 总长度返回-1 但当前下载的长度确等于文件大小
else if(progress > max)
progress = max;
else
this.progress = progress;
postInvalidate();
}


public int getMax() {
return max;
}


public void setMax(int max) {
if(max < 0){  
           throw new IllegalArgumentException("max not less than 0");  
     }  
     this.max = max;  
}



}


(3)

/**
 * 跑马灯效果
 * 
 */
public class TextviewRolling extends TextView {


/**
* @param context
*/
public TextviewRolling(Context context) {
super(context);
// TODO Auto-generated constructor stub
}


/**
* @param context
* @param attrs
* @param defStyle
*/
public TextviewRolling(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}


/**
* @param context
* @param attrs
*/
public TextviewRolling(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}


/*
* (non-Javadoc)

* @see android.widget.TextView#onFocusChanged(boolean, int,
* android.graphics.Rect)
*/
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
// TODO Auto-generated method stub
if (focused)
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}


/*
* (non-Javadoc)

* @see android.widget.TextView#onWindowFocusChanged(boolean)
*/
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
// TODO Auto-generated method stub
if (hasWindowFocus)
super.onWindowFocusChanged(hasWindowFocus);
}


/*
* (non-Javadoc)

* @see android.view.View#isFocused()
*/
@Override
@ExportedProperty(category = "focus")
public boolean isFocused() {
// TODO Auto-generated method stub
return true;
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值