• This is the third day of my participation in the August More Text Challenge.

1. Long press event

  • The long-press event is not used very often, but it can be used in some special cases.
  • For example: copy a paragraph of text is long press operation
  • Long-press events are also very similar to single-click and double-click events
  • The interface name:LongClickedListener

2. Implementation case: Long press the button to modify the text content

  • New project: ListenerApplication3

ability_main


      
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Text
        ohos:id="$+id:text1"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="text"
        ohos:text_size="100">

    </Text>

    <Button
        ohos:id="$+id:but1"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="点我"
        ohos:text_size="100"
        ohos:background_element="red">

    </Button>
</DirectionalLayout>
Copy the code

MainAbilitySlice

package com.xdr630.listenerapplication3.slice;

import com.xdr630.listenerapplication3.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;

public class MainAbilitySlice extends AbilitySlice implements Component.LongClickedListener {
    // as a member, otherwise onLongClicked does not access text components and initializes defaults
    Text text1 = null;

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

        //1. Find the textbox component and the button component
        text1 = (Text) findComponentById(ResourceTable.Id_text1);
        Button but1 = (Button) findComponentById(ResourceTable.Id_but1);

        //2. Bind long press event, bind event to whomever you click
        // When a button is long pressed, the onLongClicked method of this class executes
        but1.setLongClickedListener(this);
    }

    @Override
    public void onActive(a) {
        super.onActive();
    }

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

    @Override
    public void onLongClicked(Component component) {
        // Modify the contents of the text box
        text1.setText("Long press"); }}Copy the code
  • Run:

  • After long press the button: