Home > OS >  addTextChangedListener on Edittext of other fragment
addTextChangedListener on Edittext of other fragment

Time:10-22

    val SEARCHBAR = requireView().findViewById<EditText>(R.id.searchbar)
    //This is EditText from other fragment

    SEARCHBAR.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable) {}

        override fun beforeTextChanged(
            s: CharSequence, start: Int,
            count: Int, after: Int,
        ) {}

        override fun onTextChanged(
            str: CharSequence, start: Int,
            before: Int, count: Int,
        ){}
    })

MainFragment Has EditText and Recyclerview in ChildFragment should be changed by EditText of MainFragment.

I did above code in onViewCreated in Child Fragment , but I keep getting NullPointerException Error.

How can I use addTextChangedListener on EditText of other Fragment?

Thanks.

CodePudding user response:

hope this Kotlin sample help make it clear:

class MainFragment : Fragment() {

    private lateinit var viewModel: MainViewModel

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View {
    val view = inflater.inflate(R.layout.main_fragment, container, false)

    view.user.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) {
                userLayout.error =
                        if (s.length > userLayout.counterMaxLength) {
                            "Max character length is: ${userLayout.counterMaxLength}"
                        } else null
        }
    })
    return view
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
    // TODO: Use the ViewModel
   }
}

With this XML layout:

<android.support.design.widget.TextInputLayout
    android:id="@ id/userLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:counterMaxLength="5"
    app:counterEnabled="true"
    android:hint="user_name">

    <android.support.design.widget.TextInputEditText
        android:id="@ id/user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</android.support.design.widget.TextInputLayout>
  • Related