2016-03-08 5 views
0

У меня есть рецикла демо, но когда я запустить демо, всегда появляется сообщение об ошибке «Recycleview RecyclerView: Нет адаптер прилагается; пропуск макет»Recycleview RecyclerView: адаптер не подключен; пропуская макет

Это мой основной класс активности

public class MainActivity extends BaseActivity{ 

// private ListView mListView; 
private ArrayList<Note> noteList; 
private RecycleViewNoteListAdatper noteListAdapter; 
private SwipeRefreshLayout mSwipeRefreshLayout; 
private DrawerLayout drawerLayout; 
private View drawerView; 
private Toolbar mToolbar; 
private RecyclerView mRecycleView; 

@SuppressLint("NewApi") @Override 
protected void onCreate(Bundle savedInstanceState) { 
//  requestWindowFeature(Window.); 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    initView(); 
    initData(); 
    initListener(); 
//  colorChange(); 
    if (android.os.Build.VERSION.SDK_INT >= 21) { 
     Window window = getWindow(); 
     // 很明显,这两货是新API才有的。 
//   window.setStatusBarColor(colorBurn(R.color.colorPrimary)); 
//   window.setNavigationBarColor(colorBurn(R.color.colorPrimary)); 
    } 

} 

@SuppressLint("NewApi") 
private void initView() { 
    mRecycleView = (RecyclerView) findViewById(R.id.recycler_view); 

    mToolbar = (Toolbar) findViewById(R.id.toolbar); 
    mToolbar.setTitle("全部内容"); 
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer); 
    mToolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); 
    setSupportActionBar(mToolbar); 
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
      this, drawerLayout, mToolbar, R.string.open_string, 
      R.string.close_string); 
    actionBarDrawerToggle.syncState(); 
    drawerLayout.setDrawerListener(actionBarDrawerToggle); 
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout); 
    mSwipeRefreshLayout.setColorSchemeColors(R.color.colorPrimary); 
    mSwipeRefreshLayout.setEnabled(true); 
    mSwipeRefreshLayout 
      .setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { 
       @Override 
       public void onRefresh() { 
        // 执行刷新操作 
        new Handler().postDelayed(new Runnable() { 

         @Override 
         public void run() { 
          mSwipeRefreshLayout.setRefreshing(false); 
         } 
        }, 3000); 
       } 
      }); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 



//   fab.attachToListView(mRecycleView,); 
    ScrollDirectionListener listener= new ScrollDirectionListener() { 
      @Override 
      public void onScrollDown() { 
       LogUtils.d("ListViewFragment", "onScrollDown()"); 
      } 

      @Override 
      public void onScrollUp() { 
       LogUtils.d("ListViewFragment", "onScrollUp()"); 
      } 
     };/*, new AbsListView.OnScrollListener() { 
      @Override 
      public void onScrollStateChanged(AbsListView view, int scrollState) { 
       LogUtils.d("ListViewFragment", "onScrollStateChanged()"); 
      } 

      @Override 
      public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { 
       LogUtils.d("ListViewFragment", "onScroll()"); 
      } 
     }*/ 
    fab.attachToRecyclerView(mRecycleView, listener); 
} 

private void initData() { 
    noteList = new ArrayList<Note>(); 
    Note note = null; 
    for (int i = 0; i < 50; i++) { 
     note = new Note(); 
     String md5Encode = MD5Utils.MD5Encode(String.valueOf(System 
       .currentTimeMillis()) + i + "note"); 
     note.setNoteName(md5Encode); 
     note.setNoteMd5(md5Encode); 
     noteList.add(note); 
    } 
//  noteListAdapter = new NoteListAdatper(this, noteList); 

    //设置 RecycleView的显示方式 
    LinearLayoutManager llm= new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false); 
    mRecycleView.setLayoutManager(llm); 
    RecycleViewNoteListAdatper noteAdapter=new RecycleViewNoteListAdatper(this, noteList); 
    mRecycleView.setAdapter(noteListAdapter); 

} 

private void initListener() { 
    drawerLayout.requestDisallowInterceptTouchEvent(true); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main, menu); 
    return super.onCreateOptionsMenu(menu); 

} 

} 

Это мой RecyclerViewAdapter код

public class RecycleViewNoteListAdatper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ 
    Context mContext; 
    private LayoutInflater layoutInflater; 
    private ArrayList<Note> list; 
    public RecycleViewNoteListAdatper(Context context,ArrayList<Note> note) { 
     this.mContext=context; 
     this.list=note; 
     layoutInflater = LayoutInflater.from(context); 
    } 

    @Override 
    public ViewHolder onCreateViewHolder(ViewGroup paramViewGroup, int paramInt) { 
     return new RecyclerViewHolder(layoutInflater.inflate(R.layout.item_notelist_2, paramViewGroup),this,mContext) ; 
    } 

    @Override 
    public void onBindViewHolder(ViewHolder paramVH, int paramInt) { 
     if(!ListUtils.isEmpty(list)){ 
      Note note = list.get(paramInt); 
      ((RecyclerViewHolder)paramVH).tv_introduce.setText(note.getNoteName()); 
     } 
    } 

    @Override 
    public int getItemCount() { 
     if(!ListUtils.isEmpty(list)){ 
      return list.size(); 
     } 
     return 0; 
    } 
    public static class RecyclerViewHolder extends RecyclerView.ViewHolder implements OnClickListener{ 
     RecyclerView.Adapter<ViewHolder> mAdapter; 
     Context mContext; 
     RelativeLayout ll_container; 
     LinearLayout ll_action; 
     Button action1,action2,action3; 
     TextView tv_introduce; 
     public RecyclerViewHolder(View view,RecyclerView.Adapter<ViewHolder> adapter,Context context) { 
      super(view); 
      this.mAdapter=adapter; 
      this.mContext=context; 
      tv_introduce = (TextView) view.findViewById(R.id.item_introduce); 
      action1=(Button) view.findViewById(R.id.button1); 
      action2=(Button) view.findViewById(R.id.button2); 
      action3=(Button) view.findViewById(R.id.button3); 
      ll_container=(RelativeLayout) view.findViewById(R.id.ll_container); 
      ll_action=(LinearLayout) view.findViewById(R.id.ll_action); 


      action1.setOnClickListener(this); 
      action2.setOnClickListener(this); 
      action3.setOnClickListener(this); 

      ll_container.setOnClickListener(this); 

     } 
     @Override 
     public void onClick(View v) { 

      switch (v.getId()) { 
      case R.id.button1: 
       ToastUtils.showToast(mContext, "onClick1"); 
       break; 
      case R.id.button2: 
       ToastUtils.showToast(mContext, "onClick2"); 
       break; 
      case R.id.button3: 
       ToastUtils.showToast(mContext, "onClick3"); 
       break; 
      case R.id.ll_container: 
       Intent intent=new Intent(mContext,SimpleNoteEditActivity.class); 
       mContext.startActivity(intent); 
       break; 
      default: 
       break; 
      } 

     }  


    } 
} 
+0

У меня отладка программы, у нее есть метод конструктора RecycleViewAdapter. – Galaxy

+1

Возможный дубликат http://stackoverflow.com/questions/28510578/no-adapter-attached-skipping-layout, а также есть много ответов, связанных с этой темой. – Hima

ответ

1

Это очень распространенная проблема, которую мы используем. Вы написали эти коды внутри initData метода, который будет принимать длительный процесс, чтобы получить правильные данные, но мы должны инициализировать, что первым Так что вы можете сделать сейчас скопировать эти коды в onCreate()

LinearLayoutManager llm= new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false); 
mRecycleView.setLayoutManager(llm); 
RecycleViewNoteListAdatper noteAdapter=new RecycleViewNoteListAdatper(this, noteList); 
mRecycleView.setAdapter(noteAdapter); 

ПРИМЕЧАНИЯ : Сделайте llm, noteAdapter, noteAdapter переменной класса. Сделать noteList Пустой массив. Затем сначала установите его, чтобы повторить тот же процесс после загрузки данных, но не инициализируйте его дважды. Я всегда использую это.

+0

man u r установка неправильного адаптера здесь «noteListAdapter», это должен быть «noteAdapter». –

+0

@NaveenShriyan Ohh благодарит брата, я этого не заметил. Спасибо за поддержку. Я только что скопировал его коды .. –

+0

Спасибо, отдаст голос за u :) –

1
mRecycleView.setAdapter(noteListAdapter); 

должно быть

mRecycleView.setAdapter(noteAdapter); 
+0

Спасибо, у меня большая ошибка. – Galaxy