项目总结二——android入门项目备忘录

  • 作者:sdau20171754
  • 分类: 安卓
  • 发表日期:2019-12-31 21:23:34
  • 阅读:(220)
  • 评论(2)

最近忙着实训,最后一天有个作业,自己根据资料撸了一个简单的备忘录

项目功能:

显示所有记录,单击新建添加新备忘,长按删除

项目知识点:

包括listview用法,还有数据库操作,以及一些基本的控件,以及LinerLayout布局等

listview就是一个列表可以下滑显示,需要用到适配器,可以通过自定义适配器来自定义listview的内部显示。listview也可以点击还可以长按,通过监听触发不同操作

数据库主要是android自带的sqlite数据库,主要操作包括创建数据库和表,进行添加删除更改,具体详见代码

控件有edittext输入文本框,button按钮监听事件,textview显示文字,dailog弹出提示框,可以设置信息也可以设置按钮事件

项目实现:

1、主页面写法

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.beiwang.MainActivity"
    android:background="@mipmap/bg2"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="备忘录"
        android:textSize="30sp"
        android:textColor="#1E90FF"

        />
    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_weight="5"
        ></ListView>
   <Button
       android:id="@+id/createbutton"
       android:layout_width="wrap_content"
       android:layout_height="1dp"
       android:layout_weight="1"
       android:layout_gravity="center"
       android:text="+新建"
       android:textSize="20sp"
       android:textColor="#696969"
       />


</LinearLayout>

 

2、自定义listview样式的文件item_list.xml的写法,包括标题,创建时间,内容

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    >
    <TextView
        android:id="@+id/list_item_title"
        android:layout_width="180dp"
        android:layout_height="40dp"
        android:textSize="20sp"
        android:textColor="#FF1493"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:gravity="start|bottom"
        android:focusable="false"
        android:maxLength="10"
        android:maxLines="1"
        />
    <TextView
        android:id="@+id/list_item_time"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_toRightOf="@id/list_item_title"
        android:layout_toEndOf="@id/list_item_title"
        android:layout_alignBottom="@id/list_item_title"
        android:textColor="#808080"
        android:textSize="15sp"
        android:gravity="start|bottom"
        android:focusable="false"
        android:maxLines="1"
        android:maxLength="18"
        />
    <TextView
        android:id="@+id/list_item_body"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@id/list_item_title"
        android:textSize="20sp"
        android:layout_marginBottom="10dp"

        android:textColor="#4169E1"
        android:gravity="start|bottom"
        android:focusable="false"
        android:maxLines="1"
        android:maxLength="100"
        />
</RelativeLayout>

3、myadapter类的写法用于自定义listview,同时显示listview中的信息

package com.example.beiwang;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;

/**
 * Created by lenovo on 2019/12/30.
 */

class MyAdapter extends BaseAdapter {
    private List<Record> recordList;//数据集合
    private Context context;
    private int layoutId;

    public MyAdapter(Context context,List<Record> recordList,int layoutId){
        this.context = context;
        this.recordList = recordList;
        this.layoutId = layoutId;
    }

    @Override
    public int getCount() {
        if (recordList!=null&&recordList.size()>0)
            return recordList.size();
        else
            return 0;
    }

    @Override
    public Record getItem(int position) {
        if (recordList!=null&&recordList.size()>0)
            return recordList.get(position);
        else
            return null;
    }

    public void removeItem(int position){
        this.recordList.remove(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Record record=getItem(position);
        View view= LayoutInflater.from(context).inflate(layoutId,parent,false);
        TextView titleView=(TextView)view.findViewById(R.id.list_item_title);
        TextView bodyView=(TextView)view.findViewById(R.id.list_item_body);
        TextView timeView=(TextView)view.findViewById(R.id.list_item_time);
        String title=record.getTitleName();
        String body=record.getTextBody();
        String time=record.getCreateTime();
        titleView.setText((position+1)+"."+(title.length()>7?title.substring(0,7)+"...":title));

        bodyView.setText(body.length()>13?body.substring(0,12)+"...":body);
        timeView.setText(time);
         return view;
    }








}

 

4、record实体类,封装记录

package com.example.beiwang;

/**
 * Created by lenovo on 2019/12/30.
 */

public class Record {
    private Integer id;
    private String titleName;
    private String textBody;
    private String createTime;

    public Record()
    {}
    public Record(Integer id, String titleName, String textBody, String createTime, String noticeName) {
        this.id = id;
        this.titleName = titleName;
        this.textBody = textBody;
        this.createTime = createTime;

    }

    public Integer getId() {
        return id;
    }

    public String getTitleName() {
        return titleName;
    }

    public String getTextBody() {
        return textBody;
    }

    public String getCreateTime() {
        return createTime;
    }



    public void setTitleName(String titleName) {
        this.titleName = titleName;
    }

    public void setTextBody(String textBody) {
        this.textBody = textBody;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }


}

5、mydb数据库连接类,利用sqlite创建对应数据表,返回创建表,注意id自动增长

package com.example.beiwang;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Administrator on 2019-12-30.
 */

public class myDB extends SQLiteOpenHelper {
    public final static String TABLE_NAME_RECORD = "record";

    public final static String RECORD_ID = "id";
    public final static String RECORD_TITLE = "title_name";
    public final static String RECORD_BODY = "text_body";
    public final static String RECORD_TIME = "create_time";



    public myDB(Context context) {
        super(context, "test.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE "+TABLE_NAME_RECORD+" ("+RECORD_ID+" INTEGER PRIMARY KEY AUTOINCREMENT," +
                RECORD_TITLE+" VARCHAR(30)," +
                RECORD_BODY+" VARCHAR(50)," +
                RECORD_TIME+" VARCHAR(30) NOT NULL" + ")");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

6、mainactivity类

创建数据表,查询其中所有记录,封装到列表,然后利用listview显示

监听新建按钮,跳转到新建activity,要注意在android文件中注册

监听长按列表项,进行数据删除,先提示是否删除,确认后操作数据库删除记录,并去掉对应列表项,

监听单击选项,应该可以更新,但我没有做

package com.example.beiwang;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener {
    private ListView listview;
    private MyAdapter adapter;
    private Button createbutton;
    private myDB mydb;
    List<Record> recordList = new ArrayList<Record>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();

    }

    public void init() {
        createbutton = (Button) findViewById(R.id.createbutton);
        createbutton.setOnClickListener(this);

        listview = (ListView) findViewById(R.id.list_view);
        List<Record> recordList = new ArrayList<>();
        mydb = new myDB(this);

        SQLiteDatabase db = mydb.getReadableDatabase();
        Cursor cursor = db.query(myDB.TABLE_NAME_RECORD, null,
                null, null, null,
                null, myDB.RECORD_TIME + " DESC");
        if (cursor.moveToFirst()) {
            Record record;
            while (!cursor.isAfterLast()) {
                record = new Record();
                record.setId(Integer.valueOf(cursor.getString(cursor.getColumnIndex(myDB.RECORD_ID))));
                record.setTitleName(cursor.getString(cursor.getColumnIndex(myDB.RECORD_TITLE)));
                record.setTextBody(cursor.getString(cursor.getColumnIndex(myDB.RECORD_BODY)));
                record.setCreateTime(cursor.getString(cursor.getColumnIndex(myDB.RECORD_TIME)));
                recordList.add(record);
                cursor.moveToNext();
            }
        }
        cursor.close();
        db.close();


        adapter = new MyAdapter(this, recordList, R.layout.item_list);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(this);
        listview.setOnItemLongClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.createbutton:
                Intent intent = new Intent(MainActivity.this, EditActivity.class);
                startActivity(intent);
                MainActivity.this.finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        Record record = (Record) listview.getItemAtPosition(position);
        showDialog(record, position);
        return true;

    }

    void showDialog(final Record record, final int position) {
        final AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
        dialog.setTitle("是否删除");
        String textBody = record.getTextBody();
        dialog.setMessage(
                textBody.length() > 80 ? textBody.substring(0, 80) + "..." : textBody);
        dialog.setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SQLiteDatabase db = mydb.getWritableDatabase();
                db.delete(mydb.TABLE_NAME_RECORD,
                        mydb.RECORD_ID + "=?", new String[]{String.valueOf(record.getId())});
                db.close();
                adapter.removeItem(position);
                listview.post(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });


            }
        });
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }
        );
        dialog.show();


    }
}

7、添加备忘的页面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:background="@mipmap/bg2"
    >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="新建备忘录"
        android:textSize="30sp"
        android:textColor="#1E90FF"

        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_weight="5"
        android:orientation="vertical"

        >
        <TextView
            android:id="@+id/time"
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:layout_weight="0.5"
            android:textStyle="bold"
            android:layout_marginLeft="20dp"
            android:gravity="center_vertical"

            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="标题"
                android:textStyle="bold"
                android:layout_marginLeft="20dp"
                android:gravity="center_vertical"
                ></TextView>

            <EditText
                android:id="@+id/et_title"
                android:layout_width="150dp"
                android:layout_height="40dp"
                android:hint="请输入便签标题"
                android:textSize="12sp"
                android:layout_marginLeft="20dp"

                ></EditText>

        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_weight="3"
            android:orientation="horizontal"
           >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="内容"
                android:textStyle="bold"></TextView>

            <EditText
                android:id="@+id/et_body"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:hint="请输入便签内容"
                android:textSize="12sp"

                android:layout_marginLeft="20dp"
                android:gravity="top"
                ></EditText>

        </LinearLayout>


    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button_back"
            android:layout_gravity="left"
            android:text="返回"
            android:textColor="#fff"
            android:textSize="22sp"
            android:background="#C0C0C0"
            android:textStyle="bold"
            android:layout_margin="10dp"
            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            >
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/button_save"
                android:layout_gravity="right"
                android:text="保存"
                android:textColor="#fff"
                android:textSize="22sp"
                android:background="#1E90FF"
                android:textStyle="bold"
                android:layout_margin="10dp"
                />
        </LinearLayout>


    </LinearLayout>


</LinearLayout>

8、对应的活动主类写法

两个按钮,返回和保存,分别监听,

监听保存,首先判断输入是否合法,如果合法,就进行数据库的插入操作,插入成功,就显示提示,并跳转回主页面,

插入前获取输入的内容,以及当前时间,时间这里余外写了一个处理时间类,这里限于篇幅不展示

监听返回,判断是否有输入内容,有弹出提示框,提示是否保存,没有就返回主页面

​
package com.example.beiwang;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Date;

import static com.example.beiwang.MyFormat.getTimeStr;
import static com.example.beiwang.MyFormat.myDateFormat;

public class EditActivity extends AppCompatActivity implements View.OnClickListener {


    private myDB mydb;
    private Button btnBack;
    private Button btnSave;
    private TextView editTime;
    private EditText editTitle;
    private EditText editBody;
    private AlertDialog.Builder dialog;
    private String createDate;
    private String dispCreateDate;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        init();
        setClickListener();
        if(editTime.getText().length()==0)
            editTime.setText(dispCreateDate);

    }



    public void init()
    {
        mydb=new myDB(this);
        btnBack=(Button)findViewById(R.id.button_back);
        btnSave=(Button)findViewById(R.id.button_save);
        editTitle=(EditText)findViewById(R.id.et_title);
        editTime=(TextView)findViewById(R.id.time);
        editBody=(EditText) findViewById(R.id.et_body);
        Date date = new Date(System.currentTimeMillis());
        createDate=myDateFormat(date, DateFormatType.NORMAL_TIME);
        dispCreateDate=getTimeStr(date);




    }

    public void setClickListener()
    {
        btnSave.setOnClickListener(this);
        btnBack.setOnClickListener(this);

    }
    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View v) {
        String title;
        String body;
        title = editTitle.getText().toString();
        body = editBody.getText().toString();
        switch (v.getId()) {
            case R.id.button_save:
                if (saveFunction(title, body, createDate)) {
                    intentStart();
                }
                break;
            case R.id.button_back:
                if (!"".equals(title) || !"".equals(body)) {
                    showDialog(title, body, createDate);
                    clearDialog();

                } else
                    intentStart();
                break;
            default:
                break;
        }
    }
    void intentStart()
    {
        Intent intent=new Intent(EditActivity.this,MainActivity.class);
        startActivity(intent);
       this.finish();
    }
    boolean saveFunction(String title,String body,String createDate)
    {
        boolean flag=true;
        if("".equals(title))
        {
            Toast.makeText(this,"标题不能为空",Toast.LENGTH_LONG).show();
            flag=false;
    }
        if(title.length()>10)
        {Toast.makeText(this, "标题过长",Toast.LENGTH_LONG).show();
            flag=false;
}
    if(body.length()>100) {
        Toast.makeText(this, "标题过长", Toast.LENGTH_LONG).show();
        flag=false;
    }
    if("".equals(createDate)) {
        Toast.makeText(this, "时间格式错误", Toast.LENGTH_SHORT).show();
        flag = false;
    }
    if(flag) {
        SQLiteDatabase db;
        ContentValues values;
        db = mydb.getWritableDatabase();
        values = new ContentValues();
        values.put(myDB.RECORD_TITLE, title);
        values.put(myDB.RECORD_BODY, body);
        values.put(myDB.RECORD_TIME, createDate);
        db.insert(myDB.TABLE_NAME_RECORD, null, values);
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        db.close();
    }

    return flag;
    }
    void showDialog(final String title,final String body,final String createDate)
    {dialog=new AlertDialog.Builder(EditActivity.this);
        dialog.setTitle("提示");
        dialog.setMessage("是否保存当前编辑内容");
        dialog.setPositiveButton("保存",new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                saveFunction(title,body,createDate);
                intentStart();
            }
        });
        dialog.setNegativeButton("取消",new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                intentStart();
            }
        });
        dialog.show();
    }
    void clearDialog()
    {dialog=null;


}
}

​

效果:

 


提交评论区域

您尚未登录登录后方可评论 登录 or 注册

评论列表

o123 (2020-04-09 17:26:34):

lihailaugh

回复
o123 (2020-04-09 17:26:44) 回复 o123:

yes

回复
div>