RecyclerView增 删

、、、、、、、、、、、对应相关主布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/b1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加"
            />
        <Button
            android:id="@+id/b2"
            android:layout_toRightOf="@+id/b1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="删除"
            />
        <Button
            android:id="@+id/b3"
            android:layout_toRightOf="@+id/b1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="list"
            />
        <Button
            android:id="@+id/b4"
            android:layout_toRightOf="@+id/b1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="group"
            />

        <Button
            android:id="@+id/b5"
            android:layout_toRightOf="@+id/b1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="PB"
            />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:layout_below="@+id/one"
        android:id="@+id/id_recyclerview"
        android:divider="#ffff0000"
        android:dividerHeight="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


</RelativeLayout>
public class MainActivity extends AppCompatActivity  implements View.OnClickListener{
    String uri = "http://api.tianapi.com/social/?key=71e58b5b2f930eaf1f937407acde08fe&num=20";
    TextView id_num ,tv;
    ImageView img;
    private RecyclerView mRecyclerView;
    private HomeAdapter mAdapter;
    List<News.NewslistBean> mDatas;
    ImageLoader imagerloder;
    Button b1,b2,b3,b4,b5;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        id_num=(TextView)findViewById(R.id.id_num);
        img= (ImageView)findViewById(R.id.img);
        tv=(TextView)findViewById(R.id.tv);
        b1=(Button)findViewById(R.id.b1) ;
        b2=(Button)findViewById(R.id.b2) ;
        b3=(Button)findViewById(R.id.b3) ;
        b4=(Button)findViewById(R.id.b4) ;
        b5=(Button)findViewById(R.id.b5) ;


        mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);

        //listview的效果
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //下划线
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST));
        //groupview的效果
       /* mRecyclerView.setLayoutManager(new GridLayoutManager(this,3));*/
        //瀑布效果
       /* mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(5, StaggeredGridLayoutManager.VERTICAL));*/


            //网络判断
        boolean netWorkAvailable = NetWorkUtils.isNetWorkAvailable(this);
        if(!netWorkAvailable){
            Toast.makeText(MainActivity.this, "联网:" + netWorkAvailable, Toast.LENGTH_SHORT).show();
        }
        getData();
       b1.setOnClickListener(this);
        b2.setOnClickListener(this);
        b3.setOnClickListener(this);
        b4.setOnClickListener(this);
        b5.setOnClickListener(this);

    }

    public void getData() {
        OkHttp3Utils.getInstance().doGet(uri, new GsonObjectCallback<News>() {
            @Override
            public void onUi(News news) {

                mDatas = news.getNewslist();

                mRecyclerView.setAdapter(mAdapter = new HomeAdapter());


            }

            @Override
            public void onFailed(Call call, IOException e) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.b1:
                mAdapter.addData(1);
             break;
            case R.id.b2:
                mAdapter.removeData(1);
                break;
            case R.id.b3:
                mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
                break;
            case R.id.b4:
                mRecyclerView.setLayoutManager(new GridLayoutManager(this,3));
                break;
              case   R.id.b5:
                  mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(5, StaggeredGridLayoutManager.VERTICAL));
                break;
        }
    }


    class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder>
    {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
                    MainActivity.this).inflate(R.layout.item, parent,
                    false));
            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position)
        {
            holder.id_num.setText(mDatas.get(position).getDescription());
            holder.tv.setText(mDatas.get(position).getTitle());
             imagerloder =ImageLoader.getInstance();
            imagerloder.displayImage(mDatas.get(position).getPicUrl(),holder.img);
            // 获得该控件的所有属性
            ViewGroup.LayoutParams layoutParams = holder.tv.getLayoutParams();
            Random random = new Random();
            layoutParams.height = random.nextInt(200)+50;
            holder.tv.setLayoutParams(layoutParams);
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder
        {

            TextView id_num;
            ImageView img;
            TextView tv;
            public MyViewHolder(View view)
            {
                super(view);
                tv = (TextView)view.findViewById(R.id.tv);
                id_num = (TextView) view.findViewById(R.id.id_num);
                img = (ImageView)view.findViewById(R.id.img);
            }
        }

        /*添加和删除的方法*/
        public void addData(int position) {
            mDatas.add(position, new News.NewslistBean("sss","sss",null));
            notifyItemInserted(position);
        }

        public void removeData(int position) {
            mDatas.remove(position);
            notifyItemRemoved(position);
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的Android Studio笔记应用程序的增删改查代码示例: 1. 创建一个Note类,包含笔记的标题和内容: ``` public class Note { private int id; private String title; private String content; public Note() { } public Note(int id, String title, String content) { this.id = id; this.title = title; this.content = content; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } ``` 2. 创建一个NoteDatabaseHelper类,用于管理SQLite数据库: ``` public class NoteDatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "notes.db"; private static final int DATABASE_VERSION = 1; public NoteDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE notes (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, content TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db); } } ``` 3. 创建一个NoteAdapter类,用于显示笔记列表: ``` public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteViewHolder> { private List<Note> mNotes; private OnItemClickListener mListener; public interface OnItemClickListener { void onItemClick(Note note); } public NoteAdapter(List<Note> notes, OnItemClickListener listener) { mNotes = notes; mListener = listener; } @Override public NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_note, parent, false); return new NoteViewHolder(itemView); } @Override public void onBindViewHolder(NoteViewHolder holder, int position) { final Note note = mNotes.get(position); holder.titleTextView.setText(note.getTitle()); holder.contentTextView.setText(note.getContent()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.onItemClick(note); } }); } @Override public int getItemCount() { return mNotes.size(); } public static class NoteViewHolder extends RecyclerView.ViewHolder { public TextView titleTextView; public TextView contentTextView; public NoteViewHolder(View itemView) { super(itemView); titleTextView = (TextView) itemView.findViewById(R.id.title_text_view); contentTextView = (TextView) itemView.findViewById(R.id.content_text_view); } } } ``` 4. 创建一个NoteActivity类,用于显示笔记列表和笔记详细信息: ``` public class NoteActivity extends AppCompatActivity { private NoteDatabaseHelper mDbHelper; private List<Note> mNotes; private RecyclerView mRecyclerView; private NoteAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note); mDbHelper = new NoteDatabaseHelper(this); mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mNotes = getAllNotes(); mAdapter = new NoteAdapter(mNotes, new NoteAdapter.OnItemClickListener() { @Override public void onItemClick(Note note) { Intent intent = new Intent(NoteActivity.this, NoteDetailActivity.class); intent.putExtra("note_id", note.getId()); startActivity(intent); } }); mRecyclerView.setAdapter(mAdapter); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(NoteActivity.this, NoteDetailActivity.class); startActivity(intent); } }); } @Override protected void onResume() { super.onResume(); mNotes = getAllNotes(); mAdapter.notifyDataSetChanged(); } private List<Note> getAllNotes() { List<Note> notes = new ArrayList<>(); SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM notes", null); if (cursor.moveToFirst()) { do { int id = cursor.getInt(cursor.getColumnIndex("_id")); String title = cursor.getString(cursor.getColumnIndex("title")); String content = cursor.getString(cursor.getColumnIndex("content")); Note note = new Note(id, title, content); notes.add(note); } while (cursor.moveToNext()); } cursor.close(); db.close(); return notes; } } ``` 5. 创建一个NoteDetailActivity类,用于编辑或添加笔记: ``` public class NoteDetailActivity extends AppCompatActivity { private NoteDatabaseHelper mDbHelper; private EditText mTitleEditText; private EditText mContentEditText; private int mNoteId = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note_detail); mDbHelper = new NoteDatabaseHelper(this); mTitleEditText = (EditText) findViewById(R.id.title_edit_text); mContentEditText = (EditText) findViewById(R.id.content_edit_text); Intent intent = getIntent(); if (intent.hasExtra("note_id")) { mNoteId = intent.getIntExtra("note_id", -1); Note note = getNoteById(mNoteId); mTitleEditText.setText(note.getTitle()); mContentEditText.setText(note.getContent()); } } public void onSaveButtonClick(View view) { String title = mTitleEditText.getText().toString(); String content = mContentEditText.getText().toString(); if (title.isEmpty() || content.isEmpty()) { Toast.makeText(this, "请填写标题和内容", Toast.LENGTH_SHORT).show(); return; } if (mNoteId == -1) { addNoteToDatabase(title, content); } else { updateNoteInDatabase(mNoteId, title, content); } finish(); } private Note getNoteById(int id) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM notes WHERE _id = ?", new String[]{String.valueOf(id)}); Note note = null; if (cursor.moveToFirst()) { String title = cursor.getString(cursor.getColumnIndex("title")); String content = cursor.getString(cursor.getColumnIndex("content")); note = new Note(id, title, content); } cursor.close(); db.close(); return note; } private void addNoteToDatabase(String title, String content) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("title", title); values.put("content", content); db.insert("notes", null, values); db.close(); } private void updateNoteInDatabase(int id, String title, String content) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("title", title); values.put("content", content); db.update("notes", values, "_id = ?", new String[]{String.valueOf(id)}); db.close(); } } ``` 希望这些示例代码对您有所帮助!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值