在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
的值。
运行效果图: