HarmonyOS application development -- MyNotePad [note] [API V6] Based on TextField and Image pseudo rich text

1. Name

Name the app: MyNotePad and my notebook. The app icon adopts the default icon. Just set the app name.
The project has been placed in gitee: MyNotePad

2. Function description

  • For Hongmeng application development API V6, it may not have rich text components. Read the relevant documents. Some functions of rich text components will not take effect until AP1 V8. There is no api Hongmeng component usage about rich text on the Internet. Therefore, we decided to use TextField and Image components and ScrollView component to simulate a rich text component, which is called pseudo rich text.
  • With note editing function, you can edit text, insert pictures, and finally save them in the storage space of the application sandbox.
  • When editing, slide the input box to the left, and a delete button is displayed on the right side; Slide right to hide the delete button. It realizes this common and convenient function of Android mobile phones. Of course, you can also long press the text input box or picture to delete.
  • It realizes the selection of pictures from the system album or file, and then decodes them and displays them in the Image component. When saving, the decoded pictures are re encoded and saved in the folder created by the application sandbox.
  • The read and write operations of application sandbox storage are realized.
  • A series of folders are created, and the structure of File directory is generated through the designed storage structure, which is convenient to directly obtain the File variable call of files when storing or reading.
  • When using ListContainer to display the note list, sliding up the note list will hide the upper area and expand the vertical range of the list. Sliding down the note list will display the original function area, which realizes the function operation created by the app now.
  • After clicking "select", a selected area will appear on the left of each item in the note list. If it is selected, a green check mark will be displayed. If it does not want to be selected, the green check mark will not be displayed, realizing the deletion management function of the list items created by the app.
  • The function of searching matching notes through key sentences is realized. If there is, the notes will be loaded directly and enter the editing page. If not, toast prompt text will be displayed!

3. Key skills of APP implementation

3.1 slide the note list to change the display space, slide the note entry display left, and slide the delete key right to disappear


Implementation skills:

  • When sliding up the note list, the touch event is triggered and it is judged that it is sliding up. Then set the upper layout container component to HIDE. At this time, the upper part does not occupy space, so the vertical display space of the list is expanded. When sliding the list, if it is judged that it is sliding, set the upper layout container component to VISIBLE to achieve the purpose of restoration.
  • When sliding left on a note item, a touch event is triggered. If it is judged that it is sliding left, set the red "delete" button on the far right to VISIBLE. When sliding to the right, set it to HIDE to achieve this common deletion effect.

3.2 click "select" and a selection box will appear on the left of each note entry, and "Cancel" and "delete" will be displayed at the bottom


Implementation skills:

  • The sub layout of the ListContainer is reusable and dynamically loaded. In writing the sub layout XML, let the click selection Text on the left side be set to HIDE by default. When the user clicks "select", it will traverse all the components currently loaded by the ListContainer, and then set the click selection box on each left side to visible.
  • When you click "Cancel", set each click box to HIDE, Text to "N" and Text color to whee according to the above traversal method.
  • If the Text of a click box is "N", set its Text to“ ✔”, Set the Text color to "GREEN"; If a click box is clicked, the Text at this time is“ ✔”, Then the Text of Text is set to "N" and the Text color is set to WHIE. You can achieve the effect of selecting or not selecting after clicking.
  • Click "delete" to traverse the components that have been loaded in the ListContainer at this time. When the text content of the left click box is“ ✔”, Get the File variable of the folder where the note is located through the ListContainer's data source list (a generic ArrayList), and then delete all files in the folder through traversal. Finally, remove the data from the data source list, and finally refresh the ListContainer.

3.3 search function


Implementation skills:

  • Traverse all the short text of notes in the ListContainer at this time, and judge whether there are matching note entries by using indexof (search the text of the input box). If there are, open the note directly. If not, the Toast prompt will be displayed.

3.4 pseudo rich text editing function (text and picture)


Implementation skills:

  • Firstly, there needs to be a ScrollView component, and then TextField or Image components need to be added dynamically as needed, and there will be a recordlist (a generic ArrayList) to record the component order of the current editing area (so that the file name can be prepared according to this order when storing data and recovered according to this file name order when reading data), The "pseudo rich text" function can be realized. Look forward to the rich text components launched by the subsequent API!
  • Click "save" to first judge whether the first text input box is empty. If it is not empty, it will be saved. If it is empty, a Toast prompt will be displayed. When saving, you need to traverse each item in the recordlist and identify it according to the component type in each item. If it is TextField, you need to use the corresponding stream processing storage according to the storage method of text file. If it is Image, you need to encode it first and build the target file to package it. At this time, the record saving status is true.

3.5 get the directory structure of the note folder (important operation) (stored in the application sandbox instead of the external private storage of the application)

The folder organization of this note is as follows:

Automatically obtain the date of each day and create a daily folder dayfolder. The folder is the folder thisnote folder of each note in the editing order of that day. In this folder, the files are named and stored according to the sequence of components recorded in the recordlist. If there are already two files in the folder of the day, the folder name of the third note of the day will be incremented in order (use dayfolder. List() length+1)
[generate usernote folder directory structure] an ArrayList generic list (ArrayList StructFile dayfolders = new ArrayList < > ()) is used. There are two variables in this type of StructFile. One variable File dayfile is used to save the File of a folder on a certain day, and the other variable File [] dayfile_ Notelist files is used to save all notes in the folder of that day. In this way, the structure of usernote folder is generated, and the "handle" of all folders is held in hand for easy operation! The schematic diagram is as follows:

4. Source code

4.0 directory structure of project source files

4.1 Java source code

   4.1.1 NoteListItem.java

package com.tdtxdcxm.mynotepad.listcontaineritem;

import java.io.File;

public class NoteListItem {
    private String text = null;
    private File file = null;
    private String notedate = null;

    public NoteListItem(String text,File file) {
        this.text = text;
        this.file = file;
        getNoteDate();
    }

    public String getText() {
        return text;
    }

    public File getFile() {
        return file;
    }

    public String getNoteDate() {
        System.out.println("getNote file:"+file);
        if(file != null){
            notedate = file.getParentFile().getName();
        }
        return notedate;
    }

    public String getShortText(){
        getNoteDate();
        System.out.println("getshorttext Check:"+text+","+notedate+","+file.toString());
        if(text != null && notedate != null && file != null){

            return notedate+"\n"+text;
        }
        return "error";
    }
}

   4.1.2 NoteDataManager.java

package com.tdtxdcxm.mynotepad.notedata;

import com.tdtxdcxm.mynotepad.listcontaineritem.NoteListItem;
import com.tdtxdcxm.mynotepad.notedetails.NoteDetailInfoList;
import ohos.aafwk.ability.AbilitySlice;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.*;
import java.util.ArrayList;


class StructFile{
    private File dayfile = null;
    private File[] dayfile_notelistfiles = null;

    public File getDayfile() {
        return dayfile;
    }

    public File[] getDayfile_notelistfiles() {
        return dayfile_notelistfiles;
    }

    public StructFile(File dayfile) {
        this.dayfile = dayfile;
        this.dayfile_notelistfiles = dayfile.listFiles();
    }
}


public class NoteDataManager {
    public static File usernote = new File("/data/user/0/com.tdtxdcxm.mynotepad/usernote");

    public static ArrayList<StructFile> dayfolders = new ArrayList<>();

    public static boolean isgenerate = false;

    public static void generateUserNoteDir(){
        dayfolders.clear();
        File[] usernotelistfiles = usernote.listFiles();
        if(usernotelistfiles != null){
            for(int i = 0;i < usernotelistfiles.length;i++){
                dayfolders.add(new StructFile(usernotelistfiles[i]));
            }
            isgenerate = true;
        }
        else{
            isgenerate = false;
        }
    }

    public static void checkUserNoteDir(){
        System.out.println(usernote.toString()+"Start output usernote All directory structures in the folder:--<<");
        for(int i = 0;i < dayfolders.size();i++){
            System.out.println(dayfolders.get(i).getDayfile().toString()+":--{");
            File[] files = dayfolders.get(i).getDayfile_notelistfiles();
            for(int j = 0;j < files.length;j++){
                System.out.println(files[j].toString());
            }
            System.out.println(dayfolders.get(i).getDayfile().toString()+":--}");
        }
        System.out.println(usernote.toString()+"output usernote All directory structures in the folder are completed!-->>");
    }

    public static void isUserNoteExist(){
        if(usernote.exists()){
            System.out.println("usernote is Exist!");
            return;
        }
        System.out.println("usernote is non-existent!");
    }

    public static void readAllNoteMataForList(ArrayList<NoteListItem> listcontainerItems){
        listcontainerItems.clear();//Make sure the list is empty
        for(int i = 0;i < dayfolders.size();i++){
            File[] files = dayfolders.get(i).getDayfile_notelistfiles();
            for(int j = 0;j < files.length;j++){
                File[] detailsfiles = files[j].listFiles();
                if(detailsfiles.length != 0){
                    try{
                        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( new FileInputStream(detailsfiles[0]) ));
                        StringBuilder stringBuilder = new StringBuilder();
                        String t = null;
                        while ((t = bufferedReader.readLine()) != null) {
                            stringBuilder.append(t);
                        }
                        System.out.println(stringBuilder.toString());
                        listcontainerItems.add(new NoteListItem(stringBuilder.toString(),files[j]));
                        bufferedReader.close();
                    }
                    catch (FileNotFoundException e){
                        e.printStackTrace();
                    }
                    catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }
        for(int i = 0;i < listcontainerItems.size();i++){
            System.out.println("inspect listcontaineritem List content:"+listcontainerItems.get(i).getShortText());
        }
    }

    public static ImageSource.SourceOptions sourceOptions(){
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();

        options.formatHint = "image/jpeg";

        return options;
    }

    public static ArrayList<NoteDetailInfoList> readSomeNoteDetails(File file, AbilitySlice abilitySlice){
        System.out.println("readSomeNoteDetails inspect file-------->>"+file);
        ArrayList<NoteDetailInfoList> noteDetailInfoLists = new ArrayList<>();

        File[] files = file.listFiles();
        for(int i = 0;i < files.length;i++){
            if(files[i].getName().endsWith("txt")){
                try{
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(files[i])));
                    StringBuilder stringBuilder = new StringBuilder();
                    String t = null;
                    while ((t = bufferedReader.readLine()) != null) {
                        stringBuilder.append(t);
                    }
                    System.out.println(stringBuilder.toString());
                    noteDetailInfoLists.add(new NoteDetailInfoList(stringBuilder.toString(),file,0));

                    bufferedReader.close();
                }
                catch (FileNotFoundException e){
                    e.printStackTrace();
                }
                catch (IOException e){
                    e.printStackTrace();
                }
            }

            if(files[i].getName().endsWith("jpeg")){
                try{
                    FileInputStream fileInputStream = new FileInputStream(files[i]);
                    ImageSource imageSource = ImageSource.create(fileInputStream.getFD(),sourceOptions());
                    PixelMap pixelMap = imageSource.createPixelmap(null);
                    fileInputStream.close();
                    noteDetailInfoLists.add(new NoteDetailInfoList(pixelMap,file,1));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return noteDetailInfoLists;
    }


    public static File deleteFolderFiles(File folder){
        //Delete all files in a folder
        File[] filelist = folder.listFiles();
        for(int i = 0;i < filelist.length;i++){
            try
            {
                filelist[i].delete();
            }
            catch (SecurityException e){
                e.printStackTrace();
            }
        }
        return folder;
    }

    private NoteDataManager(){
    }

}

   4.1.3 NoteDetailInfoList.java

package com.tdtxdcxm.mynotepad.notedetails;


import java.io.File;

public class NoteDetailInfoList {
    public final String[] typename = {"TextField","Image"};
    public int type = -1;
    
    //The reference of String or PixelMap will be saved. When used, it can be forcibly converted according to type!
    public Object object = null;
    
    public File thisnotefoldername = null;

    public String getName(){
        if(type == 0 || type == 1){
            return typename[type];
        }
        return null;
    }

    public Object getObject() {
        return object;
    }

    public File getThisnotefoldername() {
        return thisnotefoldername;
    }

    public NoteDetailInfoList(Object object, File thisnotefoldername, int type) {
        this.object = object;
        this.thisnotefoldername = thisnotefoldername;
        this.type = type;

    }
}

   4.1.4 NoteListItemProvider.java

package com.tdtxdcxm.mynotepad.provider;

import com.tdtxdcxm.mynotepad.ResourceTable;
import com.tdtxdcxm.mynotepad.listcontaineritem.NoteListItem;
import com.tdtxdcxm.mynotepad.notedata.NoteDataManager;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;


import java.util.List;

public class NoteListItemProvider extends BaseItemProvider {
    private float x1 = 0,x2 = 0,y1 = 0,y2 = 0;
    private List<NoteListItem> list;
    private AbilitySlice slice;
    public static NoteListItemProvider noteListItemProvider = null;
    public static DirectionalLayout main_rootdl_ddl1 = null;

    public NoteListItemProvider(List<NoteListItem> list,AbilitySlice slice) {
        this.list = list;
        this.slice = slice;
    }

    @Override
    public int getCount() {
        return list != null?list.size():0;
    }

    @Override
    public Object getItem(int i) {
        if(list == null || (i < 0 || i >= list.size())){
            return null;
        }
        return list.get(i);
    }

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

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        final Component cmpt;
        if(component == null){
            cmpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_main_listcontainer_itemlayout,null,false);
        }
        else{
            cmpt = component;
        }

        NoteListItem noteListItem = list.get(i);
        Text selecttxt = (Text) cmpt.findComponentById(ResourceTable.Id_item_selecttxt);
        selecttxt.setText("N");
        selecttxt.setTextColor(Color.WHITE);
        selecttxt.setVisibility(Component.HIDE);
        Text text = (Text) cmpt.findComponentById(ResourceTable.Id_item_text);
        text.setText(noteListItem.getShortText());

        NoteListItemProvider.noteListItemProvider = this;

        Button button = (Button) cmpt.findComponentById(ResourceTable.Id_item_deletebut);
        button.setVisibility(Component.HIDE);

        selecttxt.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                System.out.println("selecttxt is["+selecttxt.getText()+"]");

                if(selecttxt.getText().equals("N")){
                    selecttxt.setText("✔");
                    selecttxt.setTextColor(Color.GREEN);
                    return;
                }
                if(selecttxt.getText().equals("✔")){
                    selecttxt.setText("N");
                    selecttxt.setTextColor(Color.WHITE);
                    return;
                }
            }
        });

        text.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                int action = touchEvent.getAction();
                if(action == TouchEvent.PRIMARY_POINT_DOWN){
                    MmiPoint mmiPoint = touchEvent.getPointerPosition(0);
                    x1 = mmiPoint.getX();
                    y1 = mmiPoint.getY();
                }
                if(action == TouchEvent.PRIMARY_POINT_UP){
                    MmiPoint mmiPoint = touchEvent.getPointerPosition(0);
                    x2 = mmiPoint.getX();
                    y2 = mmiPoint.getY();

                    if(x1 < x2 && Math.abs(y2 - y1) <= 90.0){
                        button.setVisibility(Component.HIDE);
                    }
                    if(x1 > x2 && Math.abs(y2 - y1) <= 90.0){
                        button.setVisibility(Component.VISIBLE);
                    }
                    if(y1 > y2 && Math.abs(x2 - x1) <= 90.0){
                        main_rootdl_ddl1.setVisibility(Component.HIDE);
                    }
                    if(y1 < y2 && Math.abs(x2 - x1) <= 90.0){
                        main_rootdl_ddl1.setVisibility(Component.VISIBLE);
                    }
                }
                return true;
            }
        });
        button.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                System.out.println("list.get(i).getFile() is"+list.get(i).getFile());
                NoteDataManager.deleteFolderFiles(list.get(i).getFile());
                list.remove(i);
                NoteListItemProvider.this.notifyDataChanged();
            }
        });
        return cmpt;
    }
}

   4.1.5 RecordComponentItem.java

package com.tdtxdcxm.mynotepad.record;

import ohos.agp.components.Component;

public class RecordComponentItem {
    public final String[] typename = {"TextField","Image"};
    public Component component;
    public int type = -1;

    public RecordComponentItem(Component component, int type) {
        this.component = component;
        this.type = type;
    }

    public String getName() {

        return "{"+type+":"+typename[type]+"}";
    }
}

   4.1.6 EditAbilitySlice.java

package com.tdtxdcxm.mynotepad.slice;

import com.tdtxdcxm.mynotepad.ResourceTable;
import com.tdtxdcxm.mynotepad.notedata.NoteDataManager;
import com.tdtxdcxm.mynotepad.notedetails.NoteDetailInfoList;
import com.tdtxdcxm.mynotepad.record.RecordComponentItem;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.media.image.ImagePacker;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;
import ohos.utils.net.Uri;

import java.io.*;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


public class EditAbilitySlice extends AbilitySlice {

    private File thisnotefoldername;//Save the notes being edited to a folder, and the File instance of the folder
    private float x1,x2,y1,y2;

    //The sequence of components used to record the current editing notes. For example, if the current editing area has an input box - picture - picture - input box in order, the recordlist records in this order.
    private ArrayList<RecordComponentItem> recordlist = new ArrayList<>();


    private DirectionalLayout edit_rootdl,edit_rootdl_ddl3;

    private Button edit_rootdl_ddl1_1_nobut,edit_rootdl_ddl1_1_savebut;

    private ScrollView edit_rootdl_ddl2_scrollview;
    private DirectionalLayout edit_rootdl_ddl2_scrollview_ddl;
    private TextField ddl2_scrollview_ddl_solidtfd;

    private Button edit_rootdl_ddl3_clearbut,edit_rootdl_ddl3_wantimagebut;

    boolean isgetimage = false;//Judge whether the picture file is successfully obtained from the album or folder
    boolean issave = false;//Judge whether the note is saved for the first time. If the note is saved for the first time, first generate a folder in which text and picture files will be stored
    boolean issavebutpress = false;//Judge whether the Save button is clicked after the change of note content; Note content change: the content of each text input box changes, the insertion or deletion of pictures, and the insertion or deletion of input boxes


    public void checkPrintlnRecordList() {
        for(int j = 0;j < recordlist.size();j++){
            if(j == 0){
                System.out.println("Start checking recordlist Value:");
            }
            if(j == recordlist.size() - 1){
                System.out.println(j+"----->>>"+recordlist.get(j).getName());
                System.out.println("inspect recordlist Value complete!");
                continue;
            }
            System.out.println(j+"----->>>"+recordlist.get(j).getName());
        }
    }
    public void clearRecordListComponents(){
        for(int i = 1;i < recordlist.size();i++){
            edit_rootdl_ddl2_scrollview_ddl.removeComponent(recordlist.get(i).component);
        }
        recordlist.clear();
        recordlist.add(new RecordComponentItem(edit_rootdl_ddl2_scrollview_ddl,0));
        checkPrintlnRecordList();
    }

    private void selectPicture(){
        //Reference tutorial
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction("android.intent.action.GET_CONTENT")
                .build();
        intent.setOperation(operation);
        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        intent.setType("image/*");
        startAbilityForResult(intent,9);
    }

    @Override
    public void onAbilityResult(int requestCode, int resultCode, Intent resultData){
        //Refer to the tutorial to modify
        if(resultData == null){
            isgetimage = false;
            return;
        }

        if(requestCode == 9){
            DirectionalLayout directionalLayout = getNewImage();
            String chooseImgUri=resultData.getUriString();

            DataAbilityHelper helper=DataAbilityHelper.creator(this.getContext());
            ImageSource imageSource = null;
            String chooseImgId=null;
            if(chooseImgUri.lastIndexOf("%3A")!=-1){
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf("%3A")+3);
            }
            else {
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf('/')+1);
            }

            Uri uri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,chooseImgId);
            try {
                FileDescriptor fd = helper.openFile(uri, "r");
                imageSource = ImageSource.create(fd, null);
                PixelMap pixelMap = imageSource.createPixelmap(null);
                ((Image)directionalLayout.getComponentAt(0)).setPixelMap(pixelMap);

                System.out.println("isgetimage is :"+isgetimage);

                edit_rootdl_ddl2_scrollview_ddl.addComponent(directionalLayout);
                recordlist.add(new RecordComponentItem(directionalLayout,1));

                directionalLayout = getNewTextField();
                edit_rootdl_ddl2_scrollview_ddl.addComponent(directionalLayout);
                recordlist.add(new RecordComponentItem(directionalLayout,0));

                isgetimage = false;
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                if (imageSource != null) {
                    imageSource.release();
                }
            }
        }

    }

    public void toastShow(String s){
        ToastDialog toastDialog = new ToastDialog(this.getContext());
        toastDialog.setText(s);
        toastDialog.setTransparent(true);
        toastDialog.setDuration(100);
        toastDialog.setAlignment(LayoutAlignment.CENTER);
        toastDialog.show();
    }
    public void commonDialogRemoveShow(String title,String content,Component component){
        CommonDialog commonDialog = new CommonDialog(this.getContext());
        commonDialog.setTitleText(title);
        commonDialog.setContentText(content);
        commonDialog.setSize(500,400);
        commonDialog.setButton(1, ""Confirm", new IDialog.ClickedListener(){
            @Override
            public void onClick(IDialog iDialog, int i) {
                int index = component.getComponentParent().getChildIndex(component);
                component.getComponentParent().removeComponent(component);
                recordlist.remove(index);

                checkPrintlnRecordList();//Check the value of the recordlist list
                issavebutpress = false;//If the input box is deleted, it will be deemed that the note content has changed, and issavebutpress will be set to false immediately
                commonDialog.destroy();
            }
        });
        commonDialog.setButton(2, "Cancel ", new IDialog.ClickedListener(){
            @Override
            public void onClick(IDialog iDialog, int i) {

                commonDialog.destroy();
            }
        });

        commonDialog.show();
    }

    public DirectionalLayout getNewTextField(){
        DirectionalLayout directionalLayout = (DirectionalLayout) LayoutScatter.getInstance(this.getContext()).parse(ResourceTable.Layout_edit_textfield_sublayout,null,false);

        TextField textField= (TextField) directionalLayout.getComponentAt(0);
        Button button = (Button) directionalLayout.getComponentAt(1);

        button.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                commonDialogRemoveShow("Text deletion prompt "," delete the indicated content? ",directionalLayout);
            }
        });
        textField.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                issavebutpress = false;//Once the content of the text input box is checked to change, issavebutpress is set to false immediately
            }
        });
        textField.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                if(touchEvent.getAction() == TouchEvent.PRIMARY_POINT_DOWN){
                    MmiPoint mmiPoint = touchEvent.getPointerPosition(0);
                    x1 = mmiPoint.getX();
                    y1 = mmiPoint.getY();
                }
                if(touchEvent.getAction() == TouchEvent.PRIMARY_POINT_UP){
                    MmiPoint mmiPoint = touchEvent.getPointerPosition(0);
                    x2 = mmiPoint.getX();
                    y2 = mmiPoint.getY();
                    if(x1 > x2 && Math.abs(y1 - y2) <= 100){
                        button.setVisibility(Component.VISIBLE);
                    }
                    if(x1 < x2 && Math.abs(y1 - y2) <= 100){
                        button.setVisibility(Component.HIDE);
                    }
                }
                return true;
            }
        });
        textField.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                commonDialogRemoveShow("Text deletion prompt "," delete the indicated content? ",directionalLayout);
            }
        });

        return directionalLayout;
    }

    public DirectionalLayout getNewImage(){
        DirectionalLayout directionalLayout = (DirectionalLayout) LayoutScatter.getInstance(this.getContext()).parse(ResourceTable.Layout_edit_image_sublayout,null,false);
        Image image = (Image) directionalLayout.getComponentAt(0);
        System.out.println("-------------->"+image);

        directionalLayout.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                commonDialogRemoveShow("Picture deletion prompt "," delete the picture? ",directionalLayout);
                issavebutpress = false;//Once the picture is deleted from the text, it is deemed that the content of the note has changed, and issavebutpress is set to false immediately
            }
        });
        image.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                commonDialogRemoveShow("Picture deletion prompt "," delete the picture? ",directionalLayout);
                issavebutpress = false;//Once the picture is deleted from the text, it is deemed that the content of the note has changed, and issavebutpress is set to false immediately
            }
        });

        return directionalLayout;
    }

    public void encodeAndSaveImage(PixelMap pixelMap,File thisnotefoldername,int orderfilename){
        ImagePacker imagePacker = ImagePacker.create();

        String filepath = Paths.get(thisnotefoldername.toString(),orderfilename+".jpeg").toString();
        File  targetfile = new File(filepath);

        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(targetfile);

            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            packingOptions.format = "image/jpeg";
            packingOptions.numberHint=1;
            packingOptions.quality = 100;

            imagePacker.initializePacking(fileOutputStream,packingOptions);
            imagePacker.addImage(pixelMap);
            imagePacker.finalizePacking();

            fileOutputStream.close();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void saveTextField(File thisnotefoldername,TextField textField,int index){
        File file = new File(thisnotefoldername.toString()+"/"+index+".txt");
        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(textField.getText().getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void showDir(){

        String DatabaseDir = this.getDatabaseDir().toString();
        String PreferencesDir = this.getPreferencesDir().toString();

        File DataDirfile = new File(this.getDataDir().toString()+"/usernote");
        DataDirfile.mkdir();//Create usernote folder

        NoteDataManager.isUserNoteExist();

        String noteeach = DataDirfile.toString();
        System.out.println("New note folder path: "+ noteeach";
        String DataDir =  this.getDataDir().toString();

        String CacheDir = this.getCacheDir().toString();
        String CodeCacheDir = this.getCodeCacheDir().toString();
        String FilesDir = this.getFilesDir().toString();

        //String ExternalCacheDir = this.getExternalCacheDir().toString();
        //String ExternalFilesDir = this.getExternalFilesDir("hello").toString();

        File file = null;

        /*
        file = new File(this.getExternalCacheDir().getParent().toString()+"/want");
        try
        {
            file.mkdir();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        */

        file = new File(this.getExternalCacheDir().getParent());
        String ss  = file.toString();
        System.out.println("ss--->>>"+ss);
        String[] slist = file.list();
        for(int i = 0;i < slist.length;i++){
            System.out.println("------->>>>>>"+slist[i]);
        }

        /*
        System.out.println("-----------------------------------------------");
        slist = this.getExternalCacheDir().list();
        System.out.println("slist.size():"+slist.length);
        for(int i = 0;i < slist.length;i++){
            System.out.println("------->>>>>>"+slist[i]);
        }

        System.out.println("External application private externalcachedir -- > "+ externalcachedir);
        System.out.println("External application private externalfilesdir -- > "+ externalfilesdir);
        System.out.println("-----------------------------------------------");
        */

        System.out.println("Start output file directory check:");
        System.out.println("database DatabaseDir-->>"+DatabaseDir);
        System.out.println("Preference key value pair database PreferencesDir-->>"+PreferencesDir);
        System.out.println("Sandbox DataDir-->>"+DataDir);
        System.out.println("Sandbox CacheDir-->>"+CacheDir);
        System.out.println("Sandbox CodeCacheDir-->>"+CodeCacheDir);
        System.out.println("Sandbox FilesDir-->>"+FilesDir);
        System.out.println("Output file directory check completed!");
    }

    public File createThisNoteFolder(){
        File file;
        Date date = new Date();//Gets the time when the Save button is clicked
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");//Format the time according to "month, year and day"
        String todayfoldername = simpleDateFormat.format(date);//Take the formatted date string as the name of today's folder
        System.out.println("Current date is--->"+todayfoldername);

        file = new File(this.getDataDir().toString()+"/usernote/"+todayfoldername);//Get the File instance of the current day's folder
        if(file.exists() == false){
            //If the current day folder does not exist, it means that the user clicks the Save button for the first time today, and the current day folder needs to be created
            file.mkdir();//Create this folder
        }

        String thisnotefoldername = file.toString()+"/"+String.valueOf(file.list().length+1);//Give this folder a name at a time
        System.out.println("thisnotefoldername-->>"+thisnotefoldername);
        file = new File(thisnotefoldername);//Get the File instance of this note folder
        file.mkdir();//Create this folder and place it in the folder of the current day


        File check_usernote_folderlist = new File(this.getDataDir().toString()+"/usernote");
        String[] usernotelist = check_usernote_folderlist.list();
        for(int i = 0;i < usernotelist.length;i++){
            System.out.println("-------check usernote>>>>>>"+usernotelist[i]);
        }


        return file;
    }



    public void initEASliceComponents(){
        edit_rootdl = (DirectionalLayout) findComponentById(ResourceTable.Id_edit_rootdl);
        edit_rootdl_ddl1_1_nobut = (Button) findComponentById(ResourceTable.Id_edit_rootdl_ddl1_1_nobut);
        edit_rootdl_ddl1_1_savebut = (Button) findComponentById(ResourceTable.Id_edit_rootdl_ddl1_1_savebut);

        edit_rootdl_ddl2_scrollview = (ScrollView) findComponentById(ResourceTable.Id_edit_rootdl_ddl2_scrollview);
        edit_rootdl_ddl2_scrollview_ddl = (DirectionalLayout) findComponentById(ResourceTable.Id_edit_rootdl_ddl2_scrollview_ddl);

        ddl2_scrollview_ddl_solidtfd = (TextField) findComponentById(ResourceTable.Id_ddl2_scrollview_ddl_solidtfd);
        ddl2_scrollview_ddl_solidtfd.setHint("It cannot be empty here. It can only be saved if it is not empty!");
        recordlist.add(new RecordComponentItem(edit_rootdl_ddl2_scrollview_ddl,0));

        edit_rootdl_ddl3 = (DirectionalLayout) findComponentById(ResourceTable.Id_edit_rootdl_ddl3);
        edit_rootdl_ddl3_clearbut = (Button) findComponentById(ResourceTable.Id_edit_rootdl_ddl3_clearbut);
        edit_rootdl_ddl3_wantimagebut = (Button) findComponentById(ResourceTable.Id_edit_rootdl_ddl3_wantimagebut);

        /*<***********************************Set listener for top cancel and save******************************/
        edit_rootdl_ddl1_1_nobut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(issavebutpress == false){
                    toastShow("Not saved!");
                }
                else{
                    toastShow("Saved!");
                }
                terminateAbility();
            }
        });
        edit_rootdl_ddl1_1_savebut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(recordlist.size() == 1 && ddl2_scrollview_ddl_solidtfd.getText().equals("")){
                    ddl2_scrollview_ddl_solidtfd.clearFocus();
                    toastShow("The content is empty and cannot be saved!");
                    return;
                }
                if(issave == true){
                    NoteDataManager.deleteFolderFiles(thisnotefoldername);
                    System.out.println("All notes in this note folder have been deleted txt and image![Warning]");
                }
                if(issave == false){
                    thisnotefoldername =  createThisNoteFolder();
                    issave = true;
                }

                checkPrintlnRecordList();
                for(int i = 0;i < recordlist.size();i++){
                    if(recordlist.get(i).type == 1){
                        Image image= (Image)((DirectionalLayout)recordlist.get(i).component).getComponentAt(0);
                        encodeAndSaveImage(image.getPixelMap(),thisnotefoldername,i);
                    }
                    if(recordlist.get(i).type == 0){
                        TextField textField = (TextField) ((DirectionalLayout)recordlist.get(i).component).getComponentAt(0);
                        saveTextField(thisnotefoldername,textField,i);
                    }
                }

                String[] ls = thisnotefoldername.list();
                for(int i = 0;i < ls.length;i++){
                    System.out.println("inspect-------------->>>>>>"+ls[i]);
                }

                NoteDataManager.generateUserNoteDir();
                NoteDataManager.checkUserNoteDir();
                toastShow("Saved!");
                ddl2_scrollview_ddl_solidtfd.clearFocus();
                issavebutpress = true;//The Save button has been pressed
            }
        });
        /************************************** * * ***********************************************************************/

        /*<********************************Set listener for bottom clear and photos****************************/
        edit_rootdl_ddl3_clearbut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                ddl2_scrollview_ddl_solidtfd.clearFocus();
                ddl2_scrollview_ddl_solidtfd.setText("");

                clearRecordListComponents();
            }
        });

        edit_rootdl_ddl3_wantimagebut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                selectPicture();
            }
        });
        /**********************************Set listener for bottom clear and photos ****************************************************>*/

        /*<*****************************Set the text content change monitoring for the inherent text input box****************************/
        ddl2_scrollview_ddl_solidtfd.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                issavebutpress = false;//Once the content of the inherent text input box changes, immediately set issavebutpress to false
                if(s.equals("") == false){
                    edit_rootdl_ddl3.setVisibility(Component.VISIBLE);
                    edit_rootdl_ddl1_1_savebut.setVisibility(Component.VISIBLE);
                }
                else{
                    edit_rootdl_ddl3.setVisibility(Component.HIDE);
                    edit_rootdl_ddl1_1_savebut.setVisibility(Component.HIDE);
                }
            }
        });
        /*******************************Set text content change monitoring for inherent text input box*/

    }


    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_edit);

        if(intent.getStringParam("type").equals("add")){
            initEASliceComponents();
        }
        if(intent.getStringParam("type").equals("detail")){
            File file = new File(intent.getStringParam("thisnotefoldername"));
            thisnotefoldername = file;
            issave = true;
            System.out.println("type:detail inspect--->issave is:"+issave+",thisnotefoldername is:"+thisnotefoldername);
            initEASliceComponents();


            ArrayList<NoteDetailInfoList> noteDetailInfoLists = NoteDataManager.readSomeNoteDetails(file,this);
            
            for(int i = 0;i < noteDetailInfoLists.size();i++){
                if(i == 0){
                    ddl2_scrollview_ddl_solidtfd.setText((String) (noteDetailInfoLists.get(i).object));
                    continue;
                }
                if(noteDetailInfoLists.get(i).type == 0){
                    DirectionalLayout directionalLayout = getNewTextField();
                    TextField textField = (TextField) directionalLayout.getComponentAt(0);
                    textField.setText((String) (noteDetailInfoLists.get(i).object));
                    edit_rootdl_ddl2_scrollview_ddl.addComponent(directionalLayout);
                    recordlist.add(new RecordComponentItem(directionalLayout,0));
                }
                if(noteDetailInfoLists.get(i).type == 1){
                    DirectionalLayout directionalLayout = getNewImage();
                    Image image = (Image) directionalLayout.getComponentAt(0);
                    image.setPixelMap((PixelMap) (noteDetailInfoLists.get(i).object));
                    edit_rootdl_ddl2_scrollview_ddl.addComponent(directionalLayout);
                    recordlist.add(new RecordComponentItem(directionalLayout,1));
                }
            }
        }

        String[] permission = {"ohos.permission.READ_USER_STORAGE","ohos.permission.WRITE_USER_STORAGE"};
        requestPermissionsFromUser(permission,0);

        showDir();
    }

    @Override
    protected void onActive() {
        super.onActive();

    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}

   4.1.7 MainAbilitySlice.java

package com.tdtxdcxm.mynotepad.slice;

import com.tdtxdcxm.mynotepad.ResourceTable;
import com.tdtxdcxm.mynotepad.listcontaineritem.NoteListItem;
import com.tdtxdcxm.mynotepad.notedata.NoteDataManager;
import com.tdtxdcxm.mynotepad.provider.NoteListItemProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

import java.util.ArrayList;


public class MainAbilitySlice extends AbilitySlice {
    private ArrayList<NoteListItem> listcontainerlist = new ArrayList<>();
    private float x1,y1,x2,y2;

    private DirectionalLayout main_rootdl_ddl1,main_rootdl_ddl2,main_rootdl_ddl3;
    private DirectionalLayout main_rootdl_ddl1_1,main_rootdl_ddl1_2;
    private ListContainer main_rootdl_ddl2_listcontainer;

    private TextField main_rootdl_ddl1_1_tfd;
    private Button main_rootdl_ddl1_1_searchbut;

    private Text main_rootdl_ddl1_2_text;
    private Button main_rootdl_ddl1_2_selectbut,main_rootdl_ddl1_2_addbut;

    private Button main_rootdl_ddl3_nobut,main_rootdl_ddl3_delbut;

    public void toastShow(String s){
        ToastDialog toastDialog = new ToastDialog(this.getContext());
        toastDialog.setText(s);
        toastDialog.setTransparent(true);
        toastDialog.setDuration(100);
        toastDialog.setAlignment(LayoutAlignment.CENTER);
        toastDialog.show();
    }

    public void initListContainer(){
        NoteDataManager.generateUserNoteDir();
        NoteDataManager.checkUserNoteDir();

        NoteDataManager.readAllNoteMataForList(listcontainerlist);

        NoteListItemProvider noteListItemProvider = new NoteListItemProvider(listcontainerlist,this);
        NoteListItemProvider.noteListItemProvider = noteListItemProvider;
        main_rootdl_ddl2_listcontainer.setItemProvider(noteListItemProvider);


        main_rootdl_ddl2_listcontainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                Intent intent = new Intent();
                intent.setParam("type","detail");

                //Pass in the folder containing the note text and image as parameters
                intent.setParam("thisnotefoldername",listcontainerlist.get(i).getFile().toString());
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName("com.tdtxdcxm.mynotepad")
                        .withAbilityName("com.tdtxdcxm.mynotepad.EditAbility")
                        .build();
                intent.setOperation(operation);
                startAbilityForResult(intent,11);
            }
        });

    }

    public void initMASComponents(){
        main_rootdl_ddl1 = (DirectionalLayout) findComponentById(ResourceTable.Id_main_rootdl_ddl1);
        main_rootdl_ddl2 = (DirectionalLayout) findComponentById(ResourceTable.Id_main_rootdl_ddl2);
        main_rootdl_ddl3 = (DirectionalLayout) findComponentById(ResourceTable.Id_main_rootdl_ddl3);
        NoteListItemProvider.main_rootdl_ddl1 = main_rootdl_ddl1;

        main_rootdl_ddl1_1 = (DirectionalLayout) findComponentById(ResourceTable.Id_main_rootdl_ddl1_1);
        main_rootdl_ddl1_2 = (DirectionalLayout) findComponentById(ResourceTable.Id_main_rootdl_ddl1_2);

        main_rootdl_ddl2_listcontainer = (ListContainer) findComponentById(ResourceTable.Id_main_rootdl_ddl2_listcontainer);

        main_rootdl_ddl1_1_tfd = (TextField) findComponentById(ResourceTable.Id_main_rootdl_ddl1_1_tfd);
        main_rootdl_ddl1_1_searchbut = (Button) findComponentById(ResourceTable.Id_main_rootdl_ddl1_1_searchbut);

        main_rootdl_ddl1_2_text = (Text) findComponentById(ResourceTable.Id_main_rootdl_ddl1_2_text);
        main_rootdl_ddl1_2_selectbut = (Button) findComponentById(ResourceTable.Id_main_rootdl_ddl1_2_selectbut);
        main_rootdl_ddl1_2_addbut = (Button) findComponentById(ResourceTable.Id_main_rootdl_ddl1_2_addbut);


        main_rootdl_ddl3_nobut = (Button) findComponentById(ResourceTable.Id_main_rootdl_ddl3_nobut);
        main_rootdl_ddl3_delbut = (Button) findComponentById(ResourceTable.Id_main_rootdl_ddl3_delbut);

        /******************************************Search button listener*******************************************/
        main_rootdl_ddl1_1_searchbut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                main_rootdl_ddl1_1_tfd.clearFocus();
                String text = main_rootdl_ddl1_1_tfd.getText();
                if(listcontainerlist.size() != 0){
                    for(int i = 0;i < listcontainerlist.size();i++){
                        String s = listcontainerlist.get(i).getText();
                        if(s.indexOf(text) != -1){
                            Intent intent = new Intent();
                            intent.setParam("type","detail");

                            //Pass in the folder containing the note text and image as parameters
                            intent.setParam("thisnotefoldername",listcontainerlist.get(i).getFile().toString());
                            Operation operation = new Intent.OperationBuilder()
                                    .withDeviceId("")
                                    .withBundleName("com.tdtxdcxm.mynotepad")
                                    .withAbilityName("com.tdtxdcxm.mynotepad.EditAbility")
                                    .build();
                            intent.setOperation(operation);
                            startAbilityForResult(intent,11);
                            return;
                        }
                    }
                    main_rootdl_ddl1_1_tfd.setText("");
                    toastShow("No notes matching this keyword found!");
                }
                else{
                    main_rootdl_ddl1_1_tfd.setText("");
                    toastShow("No notes currently! Please create a new note!");
                }
            }
        });
        /******************************************Search button listener*******************************************/

        /****************************************Title text button listener*****************************************/
        main_rootdl_ddl1_2_text.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                main_rootdl_ddl1_1_tfd.clearFocus();
            }
        });
        /****************************************Title text button listener*****************************************/

        /*<********************************Set listener for 2 function keys**********************************************/
        main_rootdl_ddl1_2_selectbut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                main_rootdl_ddl1_1_tfd.clearFocus();
                main_rootdl_ddl3.setVisibility(Component.VISIBLE);

                int count = NoteListItemProvider.noteListItemProvider.getCount();
                for(int i = 0;i < count;i++){
                    DirectionalLayout directionalLayout = (DirectionalLayout) main_rootdl_ddl2_listcontainer.getComponentAt(i);
                    directionalLayout.getComponentAt(0).setVisibility(Component.VISIBLE);
                }

            }
        });
        main_rootdl_ddl1_2_addbut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                main_rootdl_ddl1_1_tfd.clearFocus();

                Intent intent = new Intent();
                intent.setParam("type","add");
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName("com.tdtxdcxm.mynotepad")
                        .withAbilityName("com.tdtxdcxm.mynotepad.EditAbility")
                        .build();
                intent.setOperation(operation);
                startAbilityForResult(intent,10);

            }
        });
        /*********************************Set listener for 2 function keys*/

        /*<********************************Set the touch slider listener for the listContainer******************************************/

        main_rootdl_ddl2_listcontainer.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                main_rootdl_ddl1_1_tfd.clearFocus();

                int action = touchEvent.getAction();
                if(action == TouchEvent.PRIMARY_POINT_DOWN){
                    MmiPoint mmiPoint = touchEvent.getPointerPosition(0);
                    x1 = mmiPoint.getX();
                    y1 = mmiPoint.getY();
                }
                if(action == TouchEvent.PRIMARY_POINT_UP){
                    MmiPoint mmiPoint = touchEvent.getPointerPosition(0);
                    x2 = mmiPoint.getX();
                    y2 = mmiPoint.getY();

                    if(y1 > y2 && Math.abs(x2 - x1) <= 90.0){
                        main_rootdl_ddl1.setVisibility(Component.HIDE);
                        //main_rootdl_ddl3.setVisibility(Component.HIDE);
                    }
                    if(y1 < y2 && Math.abs(x2 - x1) <= 90.0){
                        main_rootdl_ddl1.setVisibility(Component.VISIBLE);
                        //main_rootdl_ddl3.setVisibility(Component.VISIBLE);
                    }
                }
                return true;
            }
        });
        /**********************************Set the touch sliding listener for listContainer*/

        /*<********************************Set up a listener for the bottom two buttons******************************************/
        main_rootdl_ddl3_nobut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                main_rootdl_ddl3.setVisibility(Component.HIDE);
                int count = NoteListItemProvider.noteListItemProvider.getCount();
                for(int i = 0;i < count;i++){
                    DirectionalLayout directionalLayout = (DirectionalLayout) main_rootdl_ddl2_listcontainer.getComponentAt(i);
                    Text text = (Text)  directionalLayout.getComponentAt(0);
                    text.setVisibility(Component.HIDE);
                    text.setText("N");
                    text.setTextColor(Color.WHITE);
                }
            }
        });
        main_rootdl_ddl3_delbut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(main_rootdl_ddl2_listcontainer.getChildCount() != 0){

                    int n = main_rootdl_ddl2_listcontainer.getChildCount();
                    System.out.println("n----->>>>"+n);
                    ArrayList<NoteListItem> t = new ArrayList<>();

                    for(int i = 0; i< n;i++){
                        DirectionalLayout directionalLayout = (DirectionalLayout) main_rootdl_ddl2_listcontainer.getComponentAt(i);
                        Text text = (Text)  directionalLayout.getComponentAt(0);
                        if(text.getText().equals("✔")){
                            NoteDataManager.deleteFolderFiles(listcontainerlist.get(i).getFile());
                        }
                        else{
                            t.add(listcontainerlist.get(i));
                        }
                    }
                    listcontainerlist.clear();
                    for(int i = 0;i < t.size();i++){
                        listcontainerlist.add(t.get(i));
                    }
                    NoteListItemProvider.noteListItemProvider.notifyDataChanged();
                    System.out.println("The data has been refreshed!!!!!!!!!");
                    t.clear();
                }
            }
        });
        /*<********************************Set up a listener for the bottom two buttons******************************************/

    }

    @Override
    public void onAbilityResult(int requestCode, int resultCode, Intent resultData){
        System.out.println("Back MainAbility Yes!");
        NoteDataManager.readAllNoteMataForList(listcontainerlist);
        NoteListItemProvider.noteListItemProvider.notifyDataChanged();
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        initMASComponents();
        initListContainer();

    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}

   4.1.8 EditAbility.java

package com.tdtxdcxm.mynotepad;

import com.tdtxdcxm.mynotepad.slice.EditAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;

public class EditAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(EditAbilitySlice.class.getName());
    }
}

   4.1.9 MainAbility.java

package com.tdtxdcxm.mynotepad;

import com.tdtxdcxm.mynotepad.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;


public class MainAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
    }
}

   4.1.10 MyApplication.java

package com.tdtxdcxm.mynotepad;

import ohos.aafwk.ability.AbilityPackage;

public class MyApplication extends AbilityPackage {
    @Override
    public void onInitialize() {
        super.onInitialize();
    }
}

4.2 XML source code

4.2.1 UI background XML source code

    4.2.1.1 background_ddl1_textfieldbutton.xml

<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <corners
        ohos:radius="100"/>
</shape>

    4.2.1.2 background_item_rootdl.xml

<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <stroke
        ohos:width="3vp"
        ohos:color="#FFF1F3FF"/>
</shape>

    4.2.1.3 background_rootdl_ddl1_1.xml

<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <corners
        ohos:radius="100"/>
    <stroke
        ohos:width="2vp"
        ohos:color="#8322B869"/>
    <solid
        ohos:color="#FFFFFFFF"/>
</shape>

4.2.2 main page and sub layout UI XML source code

    4.2.2.1 ability_edit.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:id="$+id:edit_rootdl"
    ohos:height="match_parent"
    ohos:width="match_parent"

    ohos:orientation="vertical"
    ohos:alignment="center">
    <DirectionalLayout
        ohos:id="$+id:edit_rootdl_ddl1"
        ohos:height="0"
        ohos:weight="0.5"
        ohos:width="match_parent"

        ohos:orientation="vertical"
        ohos:alignment="horizontal_center">
        <DirectionalLayout
            ohos:id="$+id:edit_rootdl_ddl1_1"
            ohos:height="match_parent"
            ohos:width="match_parent"

            ohos:orientation="horizontal"
            ohos:alignment="vertical_center">
            <Button
                ohos:id="$+id:edit_rootdl_ddl1_1_nobut"
                ohos:height="match_parent"
                ohos:width="0"
                ohos:weight="2"


                ohos:text="cancel"
                ohos:text_color="#FFC39526"
                ohos:text_size="20vp"
                ohos:text_alignment="center">
            </Button>
            <Button
                ohos:id="$+id:edit_rootdl_ddl1_1_zwbut"
                ohos:height="match_parent"
                ohos:width="0"
                ohos:weight="6"

                ohos:visibility="invisible"

                ohos:text="  "
                ohos:text_color="#FFFFFFFF"
                ohos:text_size="20vp"
                ohos:text_alignment="vertical_center">
            </Button>
            <Button
                ohos:id="$+id:edit_rootdl_ddl1_1_savebut"
                ohos:height="match_parent"
                ohos:width="0"
                ohos:weight="2"

                ohos:text="preservation"
                ohos:text_size="20vp"
                ohos:text_color="#FFC39526"
                ohos:text_alignment="center">
            </Button>
        </DirectionalLayout>
    </DirectionalLayout>
    <DirectionalLayout
        ohos:id="$+id:edit_rootdl_ddl2"
        ohos:height="0"
        ohos:weight="8"
        ohos:width="match_parent"

        ohos:orientation="vertical"
        ohos:alignment="horizontal_center"

        ohos:background_element="#FFF6F4E7">
        <ScrollView
            ohos:id="$+id:edit_rootdl_ddl2_scrollview"
            ohos:height="match_parent"
            ohos:width="match_parent"
            ohos:rebound_effect="true"
            ohos:orientation="vertical">
            <DirectionalLayout
                ohos:id="$+id:edit_rootdl_ddl2_scrollview_ddl"
                ohos:height="match_content"
                ohos:width="match_parent"

                ohos:orientation="vertical"
                ohos:alignment="horizontal_center">
                <TextField
                    ohos:id="$+id:ddl2_scrollview_ddl_solidtfd"
                    ohos:height="match_content"
                    ohos:width="match_parent"

                    ohos:multiple_lines="true"
                    ohos:max_characters="2500"
                    ohos:selection_color="blue"

                    ohos:hint_color="gray"
                    ohos:hint="Enter your notes......"
                    ohos:text_size="18vp"
                    ohos:text_alignment="start"
                    ohos:background_element="#FFD2E9D2">
                </TextField>
            </DirectionalLayout>
        </ScrollView>
    </DirectionalLayout>
    <DirectionalLayout
        ohos:id="$+id:edit_rootdl_ddl3"
        ohos:height="0"
        ohos:weight="0.5"
        ohos:width="match_parent"

        ohos:visibility="hide"

        ohos:orientation="horizontal"
        ohos:alignment="vertical_center"
        ohos:background_element="#FFFFFFFF">
        <Button
            ohos:id="$+id:edit_rootdl_ddl3_clearbut"
            ohos:height="match_parent"
            ohos:width="0"
            ohos:weight="1"

            ohos:text="empty"
            ohos:text_size="20vp"
            ohos:text_alignment="center">
        </Button>
        <Button
            ohos:id="$+id:edit_rootdl_ddl3_wantimagebut"
            ohos:height="match_parent"
            ohos:width="0"
            ohos:weight="1"

            ohos:text="picture"
            ohos:text_size="20vp"
            ohos:text_alignment="center">
        </Button>
    </DirectionalLayout>
</DirectionalLayout>

    4.2.2.2 ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:id="$+id:main_rootdl"
    ohos:height="match_parent"
    ohos:width="match_parent"

    ohos:orientation="vertical"
    ohos:alignment="center">
    <DirectionalLayout
        ohos:id="$+id:main_rootdl_ddl1"
        ohos:height="0"
        ohos:weight="1.2"
        ohos:width="match_parent"

        ohos:orientation="vertical"
        ohos:alignment="horizontal_center">
        <DirectionalLayout
            ohos:id="$+id:main_rootdl_ddl1_1"
            ohos:height="0"
            ohos:weight="1"
            ohos:width="match_parent"

            ohos:margin="10vp"

            ohos:padding="2vp"

            ohos:orientation="horizontal"
            ohos:alignment="vertical_center"
            ohos:background_element="$graphic:background_rootdl_ddl1_1">
            <TextField
                ohos:id="$+id:main_rootdl_ddl1_1_tfd"
                ohos:height="match_parent"
                ohos:width="0"
                ohos:weight="8"

                ohos:hint="Enter keywords......"
                ohos:hint_color="gray"
                ohos:text_color="blue"
                ohos:text_size="20vp"
                ohos:text_alignment="center"

                ohos:background_element="$graphic:background_ddl1_textfieldbutton">
            </TextField>
            <Button
                ohos:id="$+id:main_rootdl_ddl1_1_searchbut"
                ohos:height="match_parent"
                ohos:width="0"
                ohos:weight="2"

                ohos:text="search"
                ohos:text_size="20vp"
                ohos:text_color="#FF3B8A0F"
                ohos:text_alignment="center"

                ohos:background_element="$graphic:background_ddl1_textfieldbutton">
            </Button>
        </DirectionalLayout>
        <DirectionalLayout
            ohos:id="$+id:main_rootdl_ddl1_2"
            ohos:height="0"
            ohos:weight="1"
            ohos:width="match_parent"

            ohos:orientation="horizontal"
            ohos:alignment="vertical_center"

            ohos:background_element="#FFFFFFFF">
            <Text
                ohos:id="$+id:main_rootdl_ddl1_2_text"
                ohos:height="match_parent"
                ohos:width="0"
                ohos:weight="5.5"

                ohos:left_padding="3vp"

                ohos:text="Note"
                ohos:text_color="#FFB31FC3"
                ohos:auto_font_size="true"
                ohos:text_alignment="left">
            </Text>
            <Button
                ohos:id="$+id:main_rootdl_ddl1_2_selectbut"
                ohos:height="match_parent"
                ohos:width="0"
                ohos:weight="1.5"

                ohos:right_margin="6vp"

                ohos:text="choice"
                ohos:text_color="#FF41D7C6"
                ohos:text_size="25vp"
                ohos:text_alignment="center">
            </Button>
            <Button
                ohos:id="$+id:main_rootdl_ddl1_2_addbut"
                ohos:height="match_parent"
                ohos:width="0"
                ohos:weight="1.5"

                ohos:text="+"
                ohos:text_size="35vp"
                ohos:text_color="#FF41D7C6"
                ohos:text_alignment="center">
            </Button>
        </DirectionalLayout>
    </DirectionalLayout>
    <DirectionalLayout
        ohos:id="$+id:main_rootdl_ddl2"
        ohos:height="0"
        ohos:weight="8.2"
        ohos:width="match_parent"

        ohos:orientation="vertical"
        ohos:alignment="horizontal_center"

        ohos:background_element="#28E7F6E7">
        <ListContainer
            ohos:id="$+id:main_rootdl_ddl2_listcontainer"
            ohos:height="match_parent"
            ohos:width="match_parent"
            ohos:orientation="vertical"
            ohos:rebound_effect="true">

        </ListContainer>
    </DirectionalLayout>
    <DirectionalLayout
        ohos:id="$+id:main_rootdl_ddl3"
        ohos:height="0"
        ohos:weight="0.6"
        ohos:width="match_parent"

        ohos:visibility="hide"
        ohos:orientation="horizontal"
        ohos:alignment="vertical_center"
        ohos:background_element="#FFFFFFFF">
        <Button
            ohos:id="$+id:main_rootdl_ddl3_nobut"
            ohos:height="match_parent"
            ohos:width="0"
            ohos:weight="1"

            ohos:text="cancel"
            ohos:text_size="20vp"
            ohos:text_color="black"
            ohos:text_alignment="center">
        </Button>
        <Button
            ohos:id="$+id:main_rootdl_ddl3_delbut"
            ohos:height="match_parent"
            ohos:width="0"
            ohos:weight="1"

            ohos:text="delete"
            ohos:text_size="20vp"
            ohos:text_color="black"
            ohos:text_alignment="center">
        </Button>
    </DirectionalLayout>
</DirectionalLayout>

    4.2.2.3 edit_image_sublayout.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_content"
    ohos:width="match_parent"
    ohos:orientation="vertical"
    ohos:alignment="horizontal_center"

    ohos:background_element="#2D9F9B9B">
    <Image
        ohos:height="300vp"
        ohos:width="match_content"

        ohos:scale_mode="zoom_center"
        >
    </Image>
</DirectionalLayout>

    4.2.2.4 edit_textfield_sublayout.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_content"
    ohos:width="match_parent"
    ohos:orientation="horizontal"
    ohos:alignment="vertical_center">
    <TextField
        ohos:height="match_content"
        ohos:width="0"
        ohos:weight="9"

        ohos:multiple_lines="true"
        ohos:max_characters="2500"
        ohos:selection_color="blue"

        ohos:hint_color="gray"
        ohos:hint="Enter your notes......"
        ohos:text_size="18vp"
        ohos:text_alignment="start"
        ohos:background_element="#FFD2E9D2">
    </TextField>
    <Button
        ohos:height="match_parent"
        ohos:width="0"
        ohos:weight="1"

        ohos:visibility="hide"

        ohos:text="delete"
        ohos:text_color="red"
        ohos:text_size="18vp"
        ohos:text_alignment="center">
    </Button>
</DirectionalLayout>

    4.2.2.5 main_listcontainer_itemlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:id="$+id:item_rootdl"
    ohos:height="50vp"
    ohos:width="match_parent"
    ohos:orientation="horizontal"
    ohos:alignment="vertical_center"
    ohos:background_element="$graphic:background_item_rootdl">
    <Text
        ohos:id="$+id:item_selecttxt"
        ohos:height="match_parent"
        ohos:width="0"
        ohos:weight="1"

        ohos:text="N"
        ohos:auto_font_size="true"
        ohos:text_color="white"

        ohos:visibility="hide">
    </Text>
    <Text
        ohos:id="$+id:item_text"
        ohos:height="match_parent"
        ohos:width="0"
        ohos:weight="8"

        ohos:multiple_lines="true"
        ohos:max_text_lines="3"

        ohos:text="test"
        ohos:text_size="18vp"
        ohos:text_alignment="start"
        ohos:text_color="black">
    </Text>
    <Button
        ohos:id="$+id:item_deletebut"
        ohos:height="match_parent"
        ohos:width="0"
        ohos:weight="1"

        ohos:visibility="hide"

        ohos:text="delete"
        ohos:text_color="red"
        ohos:text_size="18vp"
        ohos:text_alignment="center">
    </Button>
</DirectionalLayout>

5. config.json

{
  "app": {
    "bundleName": "com.tdtxdcxm.mynotepad",
    "vendor": "tdtxdcxm",
    "version": {
      "code": 1000000,
      "name": "1.0.0"
    }
  },
  "deviceConfig": {},
  "module": {
    "package": "com.tdtxdcxm.mynotepad",
    "name": ".MyApplication",
    "mainAbility": "com.tdtxdcxm.mynotepad.MainAbility",
    "deviceType": [
      "phone",
      "tablet"
    ],
    "distro": {
      "deliveryWithInstall": true,
      "moduleName": "entry",
      "moduleType": "entry",
      "installationFree": false
    },
    "abilities": [
      {
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "action.system.home"
            ]
          }
        ],
        "orientation": "unspecified",
        "visible": true,
        "name": "com.tdtxdcxm.mynotepad.MainAbility",
        "icon": "$media:icon",
        "description": "$string:mainability_description",
        "label": "$string:entry_MainAbility",
        "type": "page",
        "launchType": "standard"
      },
      {
        "orientation": "unspecified",
        "name": "com.tdtxdcxm.mynotepad.EditAbility",
        "icon": "$media:icon",
        "description": "$string:editability_description",
        "label": "$string:entry_EditAbility",
        "type": "page",
        "launchType": "standard"
      }
    ],
    "reqPermissions": [
      {
        "name": "ohos.permission.READ_USER_STORAGE"
      },
      {
        "name": "ohos.permission.WRITE_USER_STORAGE"
      }
    ],
    "metaData": {
      "customizeData": [
        {
          "name": "hwc-theme",
          "value": "androidhwext:style/Theme.Emui.NoTitleBar",
          "extra": ""
        }
      ]
    }
  }
}

6. app running video (remote real machine debugging)

Notebook notes based on TextField and Image pseudo rich text

Keywords: Java harmonyos

Added by guestabc on Sat, 19 Feb 2022 23:52:37 +0200