I want to create an autoCompleteTextView in a fragment but the Array adapter is bringing an error saying that 'none of the following function can be called with the arguments supplied'. So how should I use the array adapter in a fragment class?
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val frequencyArray = ArrayList<String>()
frequencyArray.add("Daily")
frequencyArray.add("Weekly")
frequencyArray.add("Monthly")
val adapter = ArrayAdapter(
this,
com.google.android.material.R.layout.support_simple_spinner_dropdown_item,
frequencyArray
)
var autoComplete = view?.findViewById<AutoCompleteTextView>(R.id.notAuto)
autoComplete?.setAdapter(adapter)
}
CodePudding user response:
The constructor you're trying to use is this one:
public ArrayAdapter (Context context,
int resource,
List<T> objects)
The first parameter is a Context
and you're passing this
, i.e. the Fragment
. But a Fragment isn't a Context
(unlike an Activity
) so you have to grab one. Just use requireContext()
instead - you'll have one by the time onViewCreated
is called (you get it before onCreate
)
val adapter = ArrayAdapter(
requireContext(),
com.google.android.material.R.layout.support_simple_spinner_dropdown_item,
frequencyArray
)
CodePudding user response:
try this one?
class SecondFragment : Fragment() {
lateinit var autoTextView : AutoCompleteTextView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val inflate = inflater.inflate(R.layout.fragment_second, container, false)
autoTextView = inflate.findViewById(R.id.autoTextView)
val languages
= resources.getStringArray(R.array.Languages)
// Create adapter and add in AutoCompleteTextView
val adapter1
= ArrayAdapter<String>(requireContext(),
android.R.layout.simple_list_item_1, languages)
autoTextView.setAdapter(adapter1)
return inflate
}
}
and check https://prnt.sc/cQpmLyDO4WsV