点击事件实现弹出提示框修改TextView的文字信息

在Fragment中点击一个TextView控件弹出一个提示框,提示框中有输入框和确定按钮,在输入框中输入文字,点击确定按钮后提示框消失,且TextView的值改变为刚刚输入进去的文字。

要实现点击事件,首先我们需要在该Fragment的布局文件中为对应的 TextView添加一个点击事件监听器。

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click me"
    android:clickable="true"
    android:focusable="true" />

然后在Fragment中为 TextView设置点击事件的监听器,并在点击事件中显示提示框。

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class MineFragment extends Fragment {

    private TextView textView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        
        textView = view.findViewById(R.id.textView);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInputDialog();
            }
        });

        return view;
    }

    private void showInputDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("输入文字");

        final EditText input = new EditText(requireContext());
        builder.setView(input);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String text = input.getText().toString();
                textView.setText(text);
            }
        });

        builder.setNegativeButton("取消", null);

        AlertDialog dialog = builder.create();
        dialog.show();
    }
}

 

当用户点击 textView 后,会调用 showInputDialog 方法。

showInputDialog 方法创建一个带有输入框和确定按钮的对话框。用户可以在输入框中输入文字,并点击确定按钮后,会将输入的文字设置为 textView 的新值。

这样,当用户点击 textView 后,就会弹出一个提示框,允许用户输入文字,并在确定按钮点击后更新 textView 的值。

运行效果图:

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值