中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android如何實現備忘錄

發布時間:2021-11-06 17:20:47 來源:億速云 閱讀:513 作者:小新 欄目:開發技術

這篇文章主要介紹了Android如何實現備忘錄,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

    提示:文章寫完后,目錄可以自動生成,如何生成可參考右邊的幫助文檔

    一、首先創建保存數據的表

    Notedatabase,java

    package com.example.biji_1;
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    public class NoteDatabase extends SQLiteOpenHelper {
        public static final String TABLE_NAME ="notes";
        public static final String CONTENT ="content";
        public static final String ID ="_id";
        public static final String TIME ="time";
        public static final String MODE ="mode";
        public  NoteDatabase(Context context){
            super(context,"notes",null,1);
        }
        @Override
        public void onCreate(SQLiteDatabase db){
            db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + ID
                    + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + CONTENT + " TEXT NOT NULL, "
                    + TIME + " TEXT NOT NULL, "
                    + MODE + " INTEGER DEFAULT 1)");
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion){
        }
    }

    二、主界面

    MainAcitivity.java

    public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener {
        //test gittt
        private NoteDatabase dbHelper;
        private Context context = this;
        final String TAG = "tag";
        FloatingActionButton btn;
        private ListView lv;
        private NoteAdapter adapter;
        private List<Note> noteList = new ArrayList<Note>();
        private Toolbar myToolbar;
        //彈出菜單
        private PopupWindow popupWindow;
        private PopupWindow popupCover;
        private ViewGroup customView;
        private ViewGroup coverView;
        private LayoutInflater layoutInflater;
        private RelativeLayout main;
        private WindowManager wm;
        private DisplayMetrics metrics;
        private TextView setting_text;
        private ImageView setting_image;
    
        @Override
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initPrefs();
            btn = (FloatingActionButton) findViewById(R.id.fab);
            lv = findViewById(R.id.lv);
    
            myToolbar = findViewById(R.id.myToolbar);
            adapter = new NoteAdapter(getApplicationContext(), noteList);
            refreshListView();
            lv.setAdapter(adapter);
    
            setSupportActionBar(myToolbar);
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true); //設置toolbar取代actionbar
            initPopUpView();
            myToolbar.setNavigationIcon(R.drawable.ic_baseline_menu_24);
            myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "onClick: shit");
                    showPopUpView();
                }
            });
    
            lv.setOnItemClickListener(this);
    
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, EditActivity.class);
                    intent.putExtra("mode", 4);
                    startActivityForResult(intent, 0);
                }
            });
    
        }
        public void initPopUpView(){
            layoutInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            customView = (ViewGroup) layoutInflater.inflate(R.layout.setting_layout, null);
            coverView = (ViewGroup) layoutInflater.inflate(R.layout.setting_cover, null);
            main = findViewById(R.id.main_layout);
            wm = getWindowManager();
            metrics = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(metrics);
        }
        public void showPopUpView(){
            int width = metrics.widthPixels;
            int height = metrics.heightPixels;
    
            popupCover = new PopupWindow(coverView, width, height, false);
            popupWindow = new PopupWindow(customView, (int) (width * 0.7), height, true);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
    
    
            //在主界面加載成功之后 顯示彈出
            findViewById(R.id.main_layout).post(new Runnable() {
                @Override
                public void run() {
                    popupCover.showAtLocation(main, Gravity.NO_GRAVITY, 0, 0);
                    popupWindow.showAtLocation(main, Gravity.NO_GRAVITY, 0, 0);
    
                    setting_image = customView.findViewById(R.id.setting_settings_image);
                    setting_text = customView.findViewById(R.id.setting_settings_text);
    
                    setting_image.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(MainActivity.this, UserSettingsActivity.class));
                        }
                    });
    
                    setting_text.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(MainActivity.this, UserSettingsActivity.class));
                        }
                    });
    
                    coverView.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            popupWindow.dismiss();
                            return true;
                        }
                    });
    
                    popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            popupCover.dismiss();
                            Log.d(TAG, "onDismiss: test");
                        }
                    });
                }
    
            });
    
        }
        public void initPrefs(){
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
            SharedPreferences.Editor editor = sharedPreferences.edit();
            if (!sharedPreferences.contains("nightMode")) {
                editor.putBoolean("nightMode", false);
                editor.commit();
            }
        }
        // 接受startActivityForResult的結果
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data){
    
            int returnMode;
            long note_Id;
            returnMode = data.getExtras().getInt("mode", -1);
            note_Id = data.getExtras().getLong("id", 0);
    
    
            if (returnMode == 1) {  //update current note
    
                String content = data.getExtras().getString("content");
                String time = data.getExtras().getString("time");
                int tag = data.getExtras().getInt("tag", 1);
    
                Note newNote = new Note(content, time, tag);
                newNote.setId(note_Id);
                CRUD op = new CRUD(context);
                op.open();
                op.updateNote(newNote);
                op.close();
            } else if (returnMode == 0) {  // create new note
                String content = data.getExtras().getString("content");
                String time = data.getExtras().getString("time");
                int tag = data.getExtras().getInt("tag", 1);
    
                Note newNote = new Note(content, time, tag);
                CRUD op = new CRUD(context);
                op.open();
                op.addNote(newNote);
                op.close();
            } else if (returnMode == 2) { // delete
                Note curNote = new Note();
                curNote.setId(note_Id);
                CRUD op = new CRUD(context);
                op.open();
                op.removeNote(curNote);
                op.close();
            }
            else{
    
            }
            refreshListView();
            super.onActivityResult(requestCode, resultCode, data);
    
        }  //判斷筆記狀態
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main_menu, menu);
    
            //search setting
            MenuItem mSearch = menu.findItem(R.id.action_search);
            SearchView mSearchView = (SearchView) mSearch.getActionView();
    
            mSearchView.setQueryHint("請輸入搜索內容");
            mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }
    
                @Override
                public boolean onQueryTextChange(String newText) {
                    adapter.getFilter().filter(newText);
                    return false;
                }
            });
    
            return super.onCreateOptionsMenu(menu);
        }   //搜索
        @Override
        public boolean onOptionsItemSelected(MenuItem item){
            switch (item.getItemId()){
                case R.id.menu_clear:
                    new AlertDialog.Builder(MainActivity.this)
                            .setMessage("刪除全部嗎?")
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dbHelper = new NoteDatabase(context);
                                    SQLiteDatabase db = dbHelper.getWritableDatabase();
                                    db.delete("notes", null, null);
                                    db.execSQL("update sqlite_sequence set seq=0 where name='notes'");
                                    refreshListView();
                                }
                            }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create().show();
                    break;
    
            }
            return super.onOptionsItemSelected(item);
        }  //主界面刪除
        public void refreshListView(){
    
            CRUD op = new CRUD(context);
            op.open();
            // set adapter
            if (noteList.size() > 0) noteList.clear();
            noteList.addAll(op.getAllNotes());
            op.close();
            adapter.notifyDataSetChanged();
        }  //刷新list
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (parent.getId()) {
                case R.id.lv:
                    Note curNote = (Note) parent.getItemAtPosition(position);
                    Intent intent = new Intent(MainActivity.this, EditActivity.class);
                    intent.putExtra("content", curNote.getContent());
                    intent.putExtra("id", curNote.getId());
                    intent.putExtra("time", curNote.getTime());
                    intent.putExtra("mode", 3);     // MODE of 'click to edit'
                    intent.putExtra("tag", curNote.getTag());
                    startActivityForResult(intent, 1);      //collect data from edit
                    Log.d(TAG, "onItemClick: " + position);
                    break;
            }
        } //攜帶數據
    }

    2.1 activity_main.xml

    三、:EditActivity.java

    package com.example.biji_1;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.EditText;
    
    import androidx.appcompat.app.AlertDialog;
    import androidx.appcompat.widget.Toolbar;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class EditActivity extends BaseActivity {
        EditText et;
        private Toolbar myToolbar;
        private String old_content = "";
        private String old_time = "";
        private int old_Tag = 1;
        private long id = 0;
        private int openMode = 0;
        private int tag = 1;
        public Intent intent = new Intent(); // message to be sent
        private boolean tagChange = false;
        private final String TAG = "tag";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.edit_layout);
    
            myToolbar = findViewById(R.id.myToolbar);
            setSupportActionBar(myToolbar);
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true); //設置toolbar取代actionbar
    
            myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    autoSetMessage();
                    setResult(RESULT_OK, intent);
                    finish();
    
                }
            });
    
    
    
            myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    autoSetMessage();
                    setResult(RESULT_OK, intent);
                    finish();
                }
            });
            et = findViewById(R.id.et_1);
            Intent getIntent = getIntent();
            openMode = getIntent.getIntExtra("mode", 0);
    
            if (openMode == 3) {//打開已存在的note
                id = getIntent.getLongExtra("id", 0);
                old_content = getIntent.getStringExtra("content");
                old_time = getIntent.getStringExtra("time");
                old_Tag = getIntent.getIntExtra("tag", 1);
                et.setText(old_content);
                et.setSelection(old_content.length());
                Log.d("TAG","打開");
    
            }
        }
        //渲染菜單欄
        @Override
        public boolean onCreateOptionsMenu(Menu menu_1) {
            getMenuInflater().inflate(R.menu.edit_menu,menu_1);
            return super.onCreateOptionsMenu(menu_1);
        }
        @Override
        public boolean onOptionsItemSelected(MenuItem item){
            switch (item.getItemId()){
                case R.id.delete:
                    new AlertDialog.Builder(EditActivity.this)
                            .setMessage("刪除嗎?")
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (openMode == 4){ // new note
                                        intent.putExtra("mode", -1);
                                        setResult(RESULT_OK, intent);
                                    }
                                    else { // existing note
                                        intent.putExtra("mode", 2);
                                        intent.putExtra("id", id);
                                        setResult(RESULT_OK, intent);
                                    }
                                    finish();
                                }
                            }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create().show();
                    break;
            }
            return super.onOptionsItemSelected(item);
        }
        public boolean onKeyDown(int keyCode, KeyEvent event){
            if (keyCode == KeyEvent.KEYCODE_HOME){
                return true;
            }
            else if (keyCode == KeyEvent.KEYCODE_BACK){
                autoSetMessage();
                setResult(RESULT_OK, intent);
                finish();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
        public void autoSetMessage(){
            if(openMode == 4){
                if(et.getText().toString().length() == 0){
                    intent.putExtra("mode", -1); //nothing new happens.
                }
                else{
                    intent.putExtra("mode", 0); // new one note;
                    intent.putExtra("content", et.getText().toString());
                    intent.putExtra("time", dateToStr());
                    intent.putExtra("tag", tag);
                }
            }
            else {
                if (et.getText().toString().equals(old_content) && !tagChange)
                    intent.putExtra("mode", -1); // edit nothing
                else {
                    intent.putExtra("mode", 1); //edit the content
                    intent.putExtra("content", et.getText().toString());
                    intent.putExtra("time", dateToStr());
                    intent.putExtra("id", id);
                    intent.putExtra("tag", tag);
                }
            }
        }
        public String dateToStr(){
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return simpleDateFormat.format(date);
        }
    }

    3.1 edit_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/myToolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:elevation="4dp"
            app:titleTextColor="#FFEBCD"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            />
        <EditText
            android:id="@+id/et_1"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:gravity="top"
            />
    
    </LinearLayout>

    四、對筆記進行增刪查改

    CRUD.java

    package com.example.biji_1;
    
    import android.annotation.SuppressLint;
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class CRUD {
        SQLiteOpenHelper dbHandler;
        SQLiteDatabase db;
    
        private static final String[] columns = {
                NoteDatabase.ID,
                NoteDatabase.CONTENT,
                NoteDatabase.TIME,
                NoteDatabase.MODE
        };
    
        public CRUD(Context context){
            dbHandler = new NoteDatabase(context);
        }
    
        public void open(){
            db = dbHandler.getWritableDatabase();
        }
    
        public void close(){
            dbHandler.close();
        }
    
        //把note 加入到database里面
        public Note addNote(Note note){
            //add a note object to database
            ContentValues contentValues = new ContentValues();
            contentValues.put(NoteDatabase.CONTENT, note.getContent());
            contentValues.put(NoteDatabase.TIME, note.getTime());
            contentValues.put(NoteDatabase.MODE, note.getTag());
            long insertId = db.insert(NoteDatabase.TABLE_NAME, null, contentValues);
            note.setId(insertId);
            return note;
        }
    
        public Note getNote(long id){
            //get a note from database using cursor index
            Cursor cursor = db.query(NoteDatabase.TABLE_NAME,columns,NoteDatabase.ID + "=?",
                    new String[]{String.valueOf(id)},null,null, null, null);
            if (cursor != null) cursor.moveToFirst();
            Note e = new Note(cursor.getString(1),cursor.getString(2), cursor.getInt(3));
            return e;
        }
    
        @SuppressLint("Range")
        public List<Note> getAllNotes(){
            Cursor cursor = db.query(NoteDatabase.TABLE_NAME,columns,null,null,null, null, null);
    
            List<Note> notes = new ArrayList<>();
            if(cursor.getCount() > 0){
                while(cursor.moveToNext()){
                    Note note = new Note();
                    note.setId(cursor.getLong(cursor.getColumnIndex(NoteDatabase.ID)));
                    note.setContent(cursor.getString(cursor.getColumnIndex(NoteDatabase.CONTENT)));
                    note.setTime(cursor.getString(cursor.getColumnIndex(NoteDatabase.TIME)));
                    note.setTag(cursor.getInt(cursor.getColumnIndex(NoteDatabase.MODE)));
                    notes.add(note);
                }
            }
            return notes;
        } //查找筆記
    
        public int updateNote(Note note) {
            //update the info of an existing note
            ContentValues values = new ContentValues();
            values.put(NoteDatabase.CONTENT, note.getContent());
            values.put(NoteDatabase.TIME, note.getTime());
            values.put(NoteDatabase.MODE, note.getTag());
            // updating row
            return db.update(NoteDatabase.TABLE_NAME, values,
                    NoteDatabase.ID + "=?",new String[] { String.valueOf(note.getId())});
        } //更新筆記
    
        public void removeNote(Note note) {
            //remove a note according to ID value
            db.delete(NoteDatabase.TABLE_NAME, NoteDatabase.ID + "=" + note.getId(), null);
        }  //刪除筆記
    }

    4.1 note_layout.xml

    <?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:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp"
        android:paddingBottom="12dp"
        android:orientation="vertical"
        android:background="@drawable/note_shape">
    
    
        <TextView
            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Content"
            android:textSize="20dp"
            android:textColor="	#00F5FF"
            android:singleLine="true"
            />
    
        <TextView
            android:id="@+id/tv_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Time"
            android:textSize="16dp"
            android:textColor="	#00F5FF"/>
    
    
    </LinearLayout>

    五、演示效果

    5.1 登錄界面

    Android如何實現備忘錄

    哈哈界面隨自己走各位別噴

    5.2筆記界面

    Android如何實現備忘錄

    之前自己寫的

    5.3 增加記錄

    Android如何實現備忘錄

    Android如何實現備忘錄

    5.4刪除記錄

    Android如何實現備忘錄

    在主界面那個刪除是刪除全部會提示你 然后你點擊進去之后還有一個刪除那條記錄的刪除鍵 這里就不做演示了

    5.5 查找記錄

    Android如何實現備忘錄

    哈哈
    ##5.6 改記錄

    Android如何實現備忘錄

    改之前

    Android如何實現備忘錄

    改之后可以看到時間變化

    其它效果靠這樣演示不出來,源碼在下面可以自取

    感謝你能夠認真閱讀完這篇文章,希望小編分享的“Android如何實現備忘錄”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!

    向AI問一下細節

    免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

    AI

    十堰市| 安阳县| 如东县| 黔南| 平阳县| 平利县| 达尔| 屏山县| 加查县| 甘洛县| 通山县| 巨鹿县| 上思县| 岢岚县| 当阳市| 尚义县| 滕州市| 甘谷县| 屏东市| 兴城市| 铜山县| 南靖县| 绥棱县| 安达市| 平阳县| 密山市| 广宗县| 台中市| 疏勒县| 博白县| 灵宝市| 浮山县| 西宁市| 德州市| 基隆市| 乐山市| 五台县| 洪湖市| 高邑县| 涟源市| 广宗县|