У меня проблемы с работой с Spinner. У меня есть кастомный переходник для Spinner. Это код:
public class CategoriaArrayAdapter extends ArrayAdapter<Categoria> {
private Context context;
private ArrayList<Categoria> values;
public CategoriaArrayAdapter(Context context, int textViewResourceId,
ArrayList<Categoria> values) {
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
public View myCustomView(int position, @Nullable View myView, @NonNull ViewGroup parent){
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View customView = layoutInflater.inflate(R.layout.row_buscar_categoria_nothing_selected, parent, false);
TextView textCategoria = customView.findViewById(R.id.tv_categoria_empty);
textCategoria.setText(values.get(position).getNombre());
return customView;
}
@Override
public int getCount(){
return values.size();
}
@Override
public Categoria getItem(int position){
return values.get(position);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return myCustomView(position, convertView, parent);
}
@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return myCustomView(position, convertView, parent);
}
}
Да, я сделал это на Java, потому что у меня нет большого опыта работы с kotlin. Что ж, это реализация моего адаптера:
private fun eventSpinners(){
myCustomAdapter = CategoriaArrayAdapter(context, R.layout.row_buscar_categoria_nothing_selected,categoriaArray)
categoriaSpinner.adapter = myCustomAdapter
categoriaSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
Log.d("BuscarActivity", "May not work")
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Toast.makeText(context, "Works!", Toast.LENGTH_LONG).show()
}
}
}
Итак, моя проблема в том, что когда вид завышен, Spinner не показывает
первый элемент ArrayList.
И когда я нажимаю на элемент массива, ничего не происходит.
Есть идеи, в чем может быть проблема?
Обновлять:
Это мой xml строки.
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
xmlns:app = "http://schemas.android.com/apk/res-auto">
<TextView xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/tv_categoria_empty"
style = "?android:attr/spinnerItemStyle"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:textSize = "18sp"
android:text = "Seleccionar"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent"
app:layout_constraintBottom_toBottomOf = "parent"/>
</android.support.constraint.ConstraintLayout>
И счетчик прядильщика находится внутри этого блока в xml:
<android.support.constraint.ConstraintLayout
android:id = "@+id/constraint_linea"
android:layout_width = "match_parent"
android:layout_height = "50dp"
android:layout_marginEnd = "10dp"
android:layout_marginLeft = "10dp"
android:layout_marginRight = "10dp"
android:layout_marginStart = "10dp"
android:layout_marginTop = "17dp"
android:background = "@drawable/shape_button_buscar"
android:orientation = "vertical"
app:layout_constraintEnd_toEndOf = "parent"
app:layout_constraintStart_toStartOf = "parent"
app:layout_constraintTop_toBottomOf = "@id/contrasint_edit_text">
<Spinner
android:id = "@+id/spinner_linea"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_marginRight = "10dp"
android:paddingLeft = "8dp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintEnd_toEndOf = "parent"
app:layout_constraintStart_toEndOf = "@id/divider"
app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>
@Ankita xml Activity или ряд прядильщика?
Блок блесны.
Проверьте, содержит ли ваш categoryArray значения или нет, получив его размер.
Да, у него есть ценности. Проверяю с помощью LogCat
Пожалуйста, обратитесь к этому ссылка на сайт
Ваш счетчик, вероятно, заполняется, но его содержимое не отображается.
Это происходит потому, что в XML для вашего представления элемента вы использовали match_parent внутри ContsraintLayout.
Прямые дочерние элементы ContsraintLayout должны использовать 0dp вместо match_parent.
Ссылка: Установите ширину в соответствии с ограничениями в ConstraintLayout
в xml строки?
Да, XML строки. Также где-нибудь еще. Любые прямые дочерние элементы ContsraintLayout не могут использовать match_parent. Вместо этого вы должны использовать 0dp.
Все еще не работает, даже onItemSelected не работает
Интересно. Проверка getView и getDropdownView вызывается с помощью операторов журнала.
Да, они работают нормально, но onItemSelectedListener нет, и я не знаю почему!
Вы должны использовать собственный макет для представления элемента
data class Category(val title: String)
class CategoryAdapter(context: Context, private var list: List<Category>) :
ArrayAdapter<Category>(context, android.R.layout.simple_spinner_dropdown_item, list) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val textView = super.getView(position, convertView, parent) as TextView
textView.text = list[position].title
return textView
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
val textView = super.getDropDownView(position, convertView, parent) as TextView
textView.text = list[position].title
return textView
}
}
Разместите свой XML-файл.