1. 程式人生 > >安卓常用控制元件RecyclerView+HorizontalScrollView實現item側滑效果 安卓常用控制元件RecyclerView+HorizontalScrollView實現item側滑效果

安卓常用控制元件RecyclerView+HorizontalScrollView實現item側滑效果 安卓常用控制元件RecyclerView+HorizontalScrollView實現item側滑效果

安卓常用控制元件RecyclerView+HorizontalScrollView實現item側滑效果

2017年10月28日 12:23:14 閱讀數:538
																				<div class="tags-box space">
							<span class="label">個人分類:</span>
															<a class="tag-link" href="https://blog.csdn.net/mhl18820672087/article/category/7226078" target="_blank">Android studio 常用控制元件應用																</a>
						</div>
																							</div>
			<div class="operating">
													</div>
		</div>
	</div>
</div>
<article>
	<div id="article_content" class="article_content clearfix csdn-tracking-statistics" data-pid="blog" data-mod="popu_307" data-dsm="post" style="height: 2391px; overflow: hidden;">
							            <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-e4c7a3727d.css">
					<div class="htmledit_views">

   簡單來介紹下RecyclerView,首先這個控制元件要做的事類似ListView,實際上它就是為了彌補ListView的不足而出現,那麼我們來看下它的簡單應用吧!

  先上效果圖

 

   RecyclerView是新增的控制元件,所以在使用這個控制元件時必須先在app/build.gradle檔案中新增依賴閉包(dependencies)


  
  1. dependencies {
  2. compile fileTree(dir: 'libs', include: ['*.jar'])
  3. androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
  4. exclude group: 'com.android.support'
    , module: 'support-annotations'
  5. })
  6. compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
  7. compile 'com.android.support:design:26.0.0-alpha1'
  8. testCompile 'junit:junit:4.12'
  9. compile'com.android.support:recyclerview-v7:24.2.1' //RecyclerView 的依賴閉包
  10. compile 'com.google.android.gms:play-services-appindexing:8.4.0'
  11. }

新增完後點擊Sync Now同步,到這裡所有的準備工作已經完成,現在開始正式使用RecyclerView,在佈局中的新增RecyclerView,在這裡,和往常新增的控制元件稍微不同,這裡新增控制元件不能只是給出RecyclerView的名字,要將完整的包路徑給出


  
  1. <android.support.v7.widget.RecyclerView
  2. android:id= "@+id/notes_title_recycler_view"
  3. android:layout_width= "match_parent"
  4. android:layout_height= "match_parent"/>

好,到這裡,控制元件新增進來,一開始說它的功能類似於ListView,接下來當然時去新建一個子佈局(item),下面這一長串的程式碼就是我定義的子佈局,其中裡面有一個自定義控制元件

com.example.haha.note.Note_delete(實現側滑的重要控制元件,下面會詳細介紹),從這裡就可以看出如果不是安卓SDK內建的控制元件,要使用統一要給出完整的路徑


  
  1. <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
  2. android:layout_width= "match_parent"
  3. android:layout_height= "80dp"
  4. android:orientation= "vertical"
  5. android:background= "@drawable/diy_frame"
  6. android:layout_marginTop= "10dp">
  7. <com.example.haha.note.Note_delete
  8. android:layout_width= "match_parent"
  9. android:layout_height= "match_parent"
  10. android:scrollbars= "none">
  11. <LinearLayout
  12. android:layout_width= "wrap_content"
  13. android:layout_height= "match_parent"
  14. android:orientation= "horizontal">
  15. <RelativeLayout
  16. android:id= "@+id/left"
  17. android:layout_width= "match_parent"
  18. android:layout_height= "match_parent"
  19. android:background= "@drawable/item_bg">
  20. <TextView
  21. android:id= "@+id/notes_title"
  22. android:layout_width= "match_parent"
  23. android:layout_height= "match_parent"
  24. android:layout_gravity= "center"
  25. android:gravity= "center_vertical"
  26. android:maxLines= "1"
  27. android:ellipsize= "end"
  28. android:textSize= "18sp"
  29. android:paddingLeft= "10dp"
  30. android:paddingRight= "10dp"
  31. android:paddingTop= "15dp"
  32. android:paddingBottom= "15dp"
  33. />
  34. </RelativeLayout>
  35. <RelativeLayout
  36. android:id= "@+id/right"
  37. android:layout_width= "200dp"
  38. android:layout_height= "match_parent"
  39. android:layout_toRightOf= "@+id/left">
  40. <ImageView
  41. android:id= "@+id/edit_note"
  42. android:layout_width= "100dp"
  43. android:layout_height= "match_parent"
  44. android:layout_gravity= "center"
  45. android:gravity= "center"
  46. android:src= "@drawable/editor"
  47. />
  48. <ImageView
  49. android:id= "@+id/tv_delete"
  50. android:layout_width= "match_parent"
  51. android:layout_height= "match_parent"
  52. android:layout_gravity= "center"
  53. android:gravity= "center"
  54. android:layout_toRightOf= "@+id/edit_note"
  55. android:src= "@drawable/cut"
  56. />
  57. </RelativeLayout>
  58. </LinearLayout>
  59. </com.example.haha.note.Note_delete>
  60. </LinearLayout>

子佈局定義完後,接下來還是老步驟,它和ListView一樣需要一個介面卡,現在我們去建立一個java類讓它繼承RecyclerView.Adapter,下面這一大段只需要理解 onCreateViewHolder()、onBindViewHolder()和getItemCount(),因為繼承自RecyclerView.Adapter就得重寫這3個方法


  
  1. class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder>{
  2. private List<notes> mNoteList;
  3. class ViewHolder extends RecyclerView.ViewHolder{
  4. TextView noteTitleText;
  5. ImageView deleteItem;
  6. public ViewHolder(View view){
  7. super(view);
  8. noteTitleText=(TextView) view.findViewById(R.id.notes_title);
  9. deleteItem=(ImageView)view.findViewById(R.id.tv_delete);
  10. }
  11. }
  12. public NoteAdapter(List<notes> notesList){
  13. mNoteList=notesList;
  14. }
  15. @Override
  16. public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){ //載入子佈局時呼叫
  17. View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.notes_item,parent, false);
  18. item_edit=(ImageView) view.findViewById(R.id.edit_note);
  19. item_delete=(ImageView) view.findViewById(R.id.tv_delete);
  20. final ViewHolder holder= new ViewHolder(view);
  21. item_edit.setOnClickListener( new View.OnClickListener() {
  22. public void onClick(View view) { //RecyclerView的點選事件,這段程式碼和本文章無太大關係,所以可以忽略
  23. notes note=mNoteList.get(holder.getAdapterPosition());
  24. if(isTwoPane){
  25. NotesContentFragment notesContentFragment=(NotesContentFragment) getFragmentManager().findFragmentById(R.id.notes_content_fragment);
  26. notesContentFragment.refresh(note.getTitle(),note.getContent());
  27. } else {
  28. notesContentActivity.actionStart(getActivity(),note.getTitle(),note.getContent());
  29. }
  30. }
  31. });
  32. return holder;
  33. }
  34. /*
  35. 新增刪除Item
  36. */
  37. public void delete_item( List<notes> mNoteList,int position){
  38. mNoteList.remove(position);
  39. notifyItemRemoved(position);
  40. notifyItemRangeChanged(position,mNoteList.size()-position);
  41. }
  42. public void onBindViewHolder(final ViewHolder holder, final int position){

  
  1. //由onCreateViewHolder返回一個對應子佈局的holder,再由onBindViewHolder進行賦值
  2. notes note=mNoteList.get(position);
  3. holder.noteTitleText.setText(note.getTitle());
  4. holder.deleteItem.setOnClickListener( new View.OnClickListener() {
  5. @Override
  6. public void onClick(View view) {
  7. delete_item(mNoteList,position);
  8. }
  9. });
  10. }
  11. public int getItemCount(){
  12. return mNoteList.size();
  13. }
  14. }

介面卡類寫好之後,接下來介紹實現側滑的重要控制元件,com.example.haha.note.Note_delete 。這是個自定義控制元件,我們來看下它的程式碼


  
  1. package com.example.haha.note;
  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. import android.util.TypedValue;
  5. import android.view.MotionEvent;
  6. import android.view.ViewGroup;
  7. import android.widget.HorizontalScrollView;
  8. import android.widget.LinearLayout;
  9. import static android.R.id.content;
  10. /**
  11. * Created by haha on 2017/9/12.
  12. */
  13. public class Note_delete extends HorizontalScrollView{
  14. private int mScreenWidth; //螢幕寬度
  15. private int mMenuWidth; //選單寬度
  16. private boolean once;
  17. public Note_delete(Context context, AttributeSet attrs){
  18. super(context,attrs);
  19. mScreenWidth=ScreenUtil.getScreenWidth(context); //由安卓內建類ScreenUtil獲取螢幕寬度 ,注意要寫一個ScreenUtil類
  20. }
  21. protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec){
  22. /*
  23. * 自定義類是繼承自HorizontalScrollView,那麼意圖就非常明顯,就是要利用父類的水平滑動效果
  24. * 而HorizontalScrollView這個控制元件只允許放一個子控制元件,一般來說,一個控制元件是遠遠不夠,那麼就
  25. * 直接設定一個線性佈局,然後再線上性佈局裡放置任意我們想放的控制元件,這樣就解決了控制元件數量的
  26. * 限制,所以下面的getChildAt(0)讓對應的就是設定的線性佈局,獲取物件,然後再由該物件獲取布
  27. * 局中的控制元件物件,這樣所有控制元件物件都能取到*/
  28. LinearLayout wrapper=(LinearLayout) getChildAt( 0);
  29. ViewGroup menu=(ViewGroup) wrapper.getChildAt( 1); //獲取線性佈局中的第二個控制元件物件
  30. mMenuWidth=mScreenWidth/ 2;
  31. menu.getLayoutParams().width=mMenuWidth; //給獲取的控制元件物件進行屬性設定
  32. super.onMeasure(widthMeasureSpec,heightMeasureSpec);
  33. }
  34. public boolean onTouchEvent(MotionEvent ev){
  35. int action=ev.getAction();
  36. switch (action){
  37. case MotionEvent.ACTION_UP: //觸碰擡起,判斷手指滑動距離
  38. int scrollX=getScrollX();
  39. if(scrollX > mMenuWidth/ 4)
  40. this.smoothScrollTo(mMenuWidth, 0);
  41. else
  42. this.smoothScrollTo( 0, 0);
  43. return true;
  44. }
  45. return super.onTouchEvent(ev);
  46. }
  47. }


寫ScreenUtil類,用於獲取螢幕高寬度


  
  1. package com.example.haha.note;
  2. import android.content.Context;
  3. import android.util.DisplayMetrics;
  4. import android.view.WindowManager;
  5. /**
  6. * Created by haha on 2017/9/12.
  7. */
  8. public class ScreenUtil {
  9. private ScreenUtil(){
  10. throw new UnsupportedOperationException( "cannot be instantiated");
  11. }
  12. //獲得螢幕高度
  13. public static int getScreenHeight(Context context){
  14. WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
  15. DisplayMetrics outMetrics = new DisplayMetrics();
  16. wm.getDefaultDisplay().getMetrics(outMetrics);