[英]How to notify activity when a fragment's edit text has been edited (Android)?
I have an edittext in one of my fragments.我的一个片段中有一个编辑文本。 I also have a String field in my activity that starts the fragment, and every time the text changes in the edittext, I want to change the string in my activity accordingly but I'm not sure how to do that.
我的活动中还有一个字符串字段,用于启动片段,每次编辑文本中的文本更改时,我都想相应地更改活动中的字符串,但我不知道该怎么做。
Create an interface like this创建一个这样的界面
interface OnDataChangeListener { fun onChange(string: String) }
In your fragment's constructor pass an instance of this interface as a parameter在片段的构造函数中,将此接口的实例作为参数传递
class MyFragment(val onDataChangeListener: OnDataChangeListener): Fragment
Now when the text changes in the edit text, call this interface's method现在当编辑文本中的文本发生变化时,调用此接口的方法
editText.addTextChangedListener(object : TextWatcher{ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { onDataChangeListener.onChange(s.toString()) } })
Now implement this interface in our activity现在在我们的活动中实现这个接口
class MainActivity : AppCompatActivity(), OnDataChangeListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) AppUtils.addFragment(this, MyFragment(this), R.id.fragment_container) } override fun onChange(string: String) { val textView = findViewById<TextView>(R.id.textView) textView.text = string } }
That's it.就是这样。 This should give you the required output.
这应该为您提供所需的输出。
Create an interface that the Activity
implements and pass it to your Fragment
.创建
Activity
实现的接口并将其传递给您的Fragment
。 Then, add a TextWatcher
to the EditText
with editText.addTextWatcher()
inside your Fragment
, and notify the listener inside onTextChanged
.然后,在您的
Fragment
使用editText.addTextWatcher()
将TextWatcher
添加到EditText
,并通知onTextChanged
的侦听onTextChanged
。 This approach is based off the Android Docs .这种方法基于Android Docs 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.