EditText 上“完成”按钮的监听器 [复制]

java

1个回答

写回答

Ccccccccui0608

2025-06-25 04:40

+ 关注

Android
Android

如何编写EditText上“完成”按钮的监听器?

在Android应用程序中,我们经常需要在用户完成在EditText中输入文本后执行某些操作。为了实现这一功能,我们可以添加一个“完成”按钮,并为其添加监听器。这样,当用户点击“完成”按钮时,我们就可以执行相应的操作。

首先,我们需要在布局文件中添加一个EditText和一个Button。EditText用于用户输入文本,而Button则是我们的“完成”按钮。在这个例子中,我们将使用ConstrAIntLayout作为根布局。

<Androidx.constrAIntlayout.widget.ConstrAIntLayout XMLns:Android="http://schemas.Android.com/apk/res/Android"</p> XMLns:app="http://schemas.Android.com/apk/res-auto"

Android:layout_width="match_parent"

Android:layout_height="match_parent">

<EditText</p> Android:id="@+id/editText"

Android:layout_width="wrap_content"

Android:layout_height="wrap_content"

app:layout_constrAIntBottom_toTopOf="@+id/button"

app:layout_constrAIntEnd_toEndOf="parent"

app:layout_constrAIntStart_toStartOf="parent"

app:layout_constrAIntTop_toTopOf="parent" />

<Button</p> Android:id="@+id/button"

Android:layout_width="wrap_content"

Android:layout_height="wrap_content"

Android:text="完成"

app:layout_constrAIntBottom_toBottomOf="parent"

app:layout_constrAIntEnd_toEndOf="parent"

app:layout_constrAIntStart_toStartOf="parent" />

</Androidx.constrAIntlayout.widget.ConstrAIntLayout>

接下来,我们需要在Java代码中为按钮添加监听器,并在其回调方法中执行相应的操作。在这个例子中,我们将在点击“完成”按钮后,将EditText中的文本显示在Toast中。

import Android.os.Bundle;

import Android.view.View;

import Android.widget.Button;

import Android.widget.EditText;

import Android.widget.Toast;

import Androidx.appcompat.app.AppCompatActivity;

public class MAInActivity extends AppCompatActivity {

private EditText editText;

private Button button;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setcontentView(R.layout.activity_mAIn);

editText = findViewById(R.id.editText);

button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String text = editText.getText().toString();

Toast.makeText(MAInActivity.this, text, Toast.LENGTH_SHORT).show();

}

});

}

}

以上就是如何编写EditText上“完成”按钮的监听器的示例代码。当用户在EditText中输入文本后,点击“完成”按钮,应用程序将显示一个Toast,其中包含输入的文本。你可以根据自己的需求修改这个示例代码,并在“完成”按钮的监听器中执行任何其他操作。

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号