项目地址
https://gitee.com/heziyan_code/note-book
项目结构
- Room数据库:AppDatabase/User/UserDao
- Main界面:将List中的内容显示出来
- Edit界面:编辑内容
Room数据库
关于Room的基本用法请看官网介绍:https://developer.android.google.cn/training/data-storage/room
定义id主键与content内容
@Entity
public class User {
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo
public String content;
}
创造增删改查方法
@Dao
public interface UserDao {
@Insert
public void addContent(User user);
@Query("SELECT * FROM user")
public List<User> showThis();
@Delete
public void delete(User user);
@Query("UPDATE user SET content = :content WHERE id = :id")
public int updateUser(String content,int id);
@Update
public void updateUser(User... users);
}
创建主视图
创造布局界面
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/darker_gray"
android:orientation="vertical" >
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="记事本列表"
android:textSize="20sp"
android:paddingTop="10dp"
android:paddingBottom="5dp"
android:background="#000"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/listview"
android:background="#000"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<Button
android:id="@+id/btn_editnote"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/black"
android:layout_gravity="center"
android:text="添加备忘录"
android:textSize="20sp" />
</LinearLayout>
显示效果
在Activity中为按钮和item添加事件与数据
public class MainActivity extends Activity {
private Button btn_editnote;
private RecyclerView mrmain;
private AppDatabase db;
private UserDao dao;
private SharedPreferences spf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_editnote = findViewById(R.id.btn_editnote);
btn_editnote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,EditView.class);
Bundle bundle = new Bundle();
bundle.putInt("num",-1);
intent.putExtras(bundle);
startActivity(intent);
}
});
//数据库连接
db = Room.databaseBuilder(this,AppDatabase.class,"test").allowMainThreadQueries().build();
dao = db.userDao();
List<User> users = dao.showThis();
// spf = getSharedPreferences("data",MODE_PRIVATE);
// String name = spf.getString("name", "");
// int id_update = spf.getInt("id_update", 0);
// System.out.println(id_update+":"+name);
// User userabc = new User();
// userabc.id = id_update;
// userabc.content = name;
// int i = dao.updateUser(name,id_update);
// System.out.println("更新了"+i+"条数据");
mrmain = findViewById(R.id.listview);
mrmain.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mrmain.addItemDecoration(new MyDecortion());
mrmain.setAdapter(new CustomAdapter(users, MainActivity.this, new CustomAdapter.OnItemClickListener() {
@Override
public void onClick(int pos,User user) {
Intent intent = new Intent(MainActivity.this,EditView.class);
Bundle bundle = new Bundle();
bundle.putInt("id",pos);
bundle.putString("content",users.get(pos).content);
intent.putExtras(bundle);
//修改时先删除该数据
dao.delete(user);
startActivity(intent);
}
@Override
public void onLongClick(int pos, User user) {
Toast.makeText(MainActivity.this,"这是第"+pos,Toast.LENGTH_SHORT).show();
//对话框确认删除
onCreateDialog(user).show();
}
}));
}
@Override
protected void onResume() {
super.onResume();
onCreate(null);
}
public Dialog onCreateDialog(User user) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("确认删除?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
dao.delete(user);
onCreate(null);//刷新界面
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
class MyDecortion extends RecyclerView.ItemDecoration{
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.set(0,0,0,1);
}
}
}
与RecycleView相关的Adapter
Adapter详解https://www.cnblogs.com/java-six/p/15863312.html
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private List<User> users;
private Context context;
private OnItemClickListener listener;
public CustomAdapter(List<User> users,Context context,OnItemClickListener listener) {
this.users = users;
this.context = context;
this.listener = listener;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false));
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
holder.textView.setText(users.get(position).content);
holder.tv_1.setText(ft.format(date));
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
listener.onLongClick(position,users.get(position));
return false;
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.onClick(position,users.get(position));
}
});
}
@Override
public int getItemCount() {
return users.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private TextView textView,tv_1;
public ViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.tv_content);
tv_1 = itemView.findViewById(R.id.tv_date);
}
}
public interface OnItemClickListener{
void onClick(int pos,User user);
void onLongClick(int pos,User user);
}
}
Edit界面
功能:点击按钮挑传到空白界面,点击item跳转到修改界面
编辑界面展示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btn_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/black"
android:textColor="#fff"
android:text="取消" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/black"
android:layout_gravity="center"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#fff"
android:text="编辑备忘录"
android:textSize="20sp" />
<TextView
android:id="@+id/tv_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="" />
</LinearLayout>
<Button
android:id="@+id/btn_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/black"
android:textColor="#fff"
android:text="保存" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="2dp"
android:orientation="vertical" >
<EditText
android:id="@+id/et_content"
android:textColor="#fff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/black"
android:textSize="20sp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
EditActivity逻辑跳转
public class EditView extends AppCompatActivity {
public AppDatabase db;
private EditText et_content;
private Button btn_cancel,btn_ok;
private Bundle bundle;
private SharedPreferences spf;
private SharedPreferences.Editor editor;
private int i = 0;
private User user = new User();
private UserDao dao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_view);
et_content = findViewById(R.id.et_content);
btn_ok = findViewById(R.id.btn_ok);
btn_cancel = findViewById(R.id.btn_cancel);
db = Room.databaseBuilder(this,AppDatabase.class,"test").allowMainThreadQueries().build();
dao = db.userDao();
bundle = getIntent().getExtras();
int num = bundle.getInt("num");
int idnum = bundle.getInt("id");
String content = bundle.getString("content");
User user_yuanlai = new User();
user_yuanlai.id = idnum;
user_yuanlai.content = content;
if(num<0) {
i = 1;
btn_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
User user = new User();
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String s = et_content.getText().toString();
user.content = s;
// user.date = ft.format(dNow);
dao.addContent(user);
Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
onBackPressed();
}
});
}else{
dao.delete(user_yuanlai);
System.out.println(idnum+":"+content);
et_content.setText(content);
user.content = content;
btn_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int id = bundle.getInt("idnum");
String s = et_content.getText().toString();
spf = getSharedPreferences("data",MODE_PRIVATE);
editor = spf.edit();
user.content = s;
editor.putString("name",s);
editor.putInt("id_update",idnum);
editor.apply();
dao.updateUser(user);
//更新无效
dao.addContent(user);
i = 1;
Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
onBackPressed();
}
});
}
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(EditView.this,MainActivity.class);
startActivity(intent);
onBackPressed();
}
});
}
@Override
protected void onPause() {
super.onPause();
if(i==0)
dao.addContent(user);
}
}