#java #android-studio #listview #android-fragments #floating-action-button
Вопрос:
Я новичок в использовании Java и Android Studio и я в тупике. Я создал приложение с нижней навигацией, и оно отлично работает. Я пытаюсь использовать плавающую кнопку действия для создания записей списка в представлении списка. Я создал адаптер для представления списка и XML для него, но когда я на самом деле нажимаю на вкладку, ничего не отображается. Я думаю, что проблема может заключаться в использовании onCreate против onCreateView, но, поскольку я новичок, я не совсем уверен, что мне следует размещать там. В моем коде фрагмент загружается, не показывая ничего, кроме заголовка фрагмента. Я перестал использовать onCreateView и поместил все в onCreate, потому что мой фрагмент выходил из строя. Любая помощь будет признательна.
Фрагмент Java:
общий класс DashboardFragment расширяет фрагмент {
private DashboardViewModel dashboardViewModel;
private FragmentDashboardBinding binding;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
ListView ListView;
EditText editText;
public String test;
public void onCreate(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editText = (EditText) getView().findViewById(R.id.editText);
listItems = new ArrayList<String>();
listItems.add("Let's see where this ends up");
ListView = (ListView) getView().findViewById(R.id.ListView);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listItems);
ListView.setAdapter(adapter);
binding.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fab:
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
}
}
}
);
ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT)
.show();
}
});
dashboardViewModel = new ViewModelProvider(this).get(DashboardViewModel.class);
binding = FragmentDashboardBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textDashboard;
dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}}
Фрагмент XML:
<TextView
android:id="@ id/textview_first8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginStart="153dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="154dp"
android:text="@string/title_dashboard"
android:textColor="@color/teal_font"
android:textSize="28sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@ id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="invisible"/>
<ListView
android:id="@ id/ListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="@ id/textview_first8"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@ id/text_dashboard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="invisible"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@ id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginEnd="32dp"
android:layout_marginBottom="88dp"
android:clickable="true"
android:src="@android:drawable/ic_menu_add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
Комментарии:
1. виды вашего фрагмента заключены внутри
ViewGroup
правого? напримерConstraintLayout
, илиLinearLayout
2. Если вы используете
ConstraintLayout
, используйте ограничения правильно. Например, ограничения дляTextView
@ id/text_dashboard устанавливаются для заполнения экрана3. Да, они находятся под ограничением.