Android RecycleView的基本式

參考自:http://givemepass.blogspot.tw/2015/12/recyclerview.html

在MainActivity中的onCreate()加入:

java.util.ArrayList<String> myDataset = new java.util.ArrayList<>();
for(int i = 0; i < 100; i++){
    myDataset.add(Integer.toString(i));
}
SearchRecycleAdapter mAdapter = new SearchRecycleAdapter(myDataset);
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.queryMainSearchView);
LinearLayoutManager layoutManager = new LinearLayoutManager(QueryMainSearchActivity.this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mAdapter);

在MainActivity中加入:

public class SearchRecycleAdapter extends android.support.v7.widget.RecyclerView.Adapter<SearchRecycleAdapter.ViewHolder> {
    private java.util.List<String> mData;
    public SearchRecycleAdapter(java.util.List<String> data) {
        this.mData = data;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.mTextView.setText(mData.get(position));
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(QueryMainSearchActivity.this, "Item " + " is clicked.", Toast.LENGTH_SHORT).show();
            }
        });
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(QueryMainSearchActivity.this, "Item " + " is long clicked.", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public class ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {
        public TextView mTextView;
        public ViewHolder(View v) {
            super(v);
            mTextView = (TextView) v.findViewById(R.id.info_text);
        }
    }
}
廣告

About fenjj

Perfect !!??...
本篇發表於 Uncategorized。將永久鏈結加入書籤。

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s