TextView.setView () не обновляет текст - PullRequest
1 голос
/ 26 марта 2020

Из фрагмента я запускаю активность, которая открывает новый фрагмент. Также я передаю строковое значение из первого фрагмента (AllDishes) по активности в последний фрагмент (DishDetailView) через намерение. Фрагмент (DishDetailView) устанавливается как контекст для макета (fragment_dishdetailview), но когда я пытаюсь установить переданный текст, представление не обновляется.

Когда я отлаживаю свое приложение Строковый параметр ("Test"), кажется, передан, а также текст TextView name, кажется, установлен правильно, как вы можете видеть на скриншоте ниже, но каким-то образом пользовательский интерфейс (fragment_dishdetailview) не обновляется, он просто пуст.

Я не уверен, является ли обновление пользовательского интерфейса или способ передачи значения из одного фрагмента в другой. Моя цель - открыть фрагмент (DishDetailView) из фрагмента (AllDishes) и передать строку из первого фрагмента во второй. Так что на самом деле мне не нужно задание, но без меня я не смог пройти Струну.

enter image description here

AllDishes (фрагмент)

@Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Dish dish = ca.getItem(position);

                Intent intent = new Intent(rootView.getContext(), DishDetailsViewActivity.class);
                intent.putExtra("nameToPass" , dish.name);
                startActivity(intent);
            }

DishDetailView (фрагмент)

public class DishDetailView extends Fragment {

    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        View rootView = inflater.inflate(R.layout.fragment_dishdetailview, container, false);

        String tempHolder = getActivity().getIntent().getStringExtra("nameToPass");

        TextView name = rootView.findViewById(R.id.textview_view_dishName);

        name.setText(tempHolder);

        rootView.invalidate();

        return inflater.inflate(R.layout.fragment_dishdetailview, container, false);
    }
}

DishDetailsViewActivity (активность)

public class DishDetailsViewActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dish_details_view);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }
}

фрагмент_dishdetailview. xml (макет фрагмента)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/screen_background"
    tools:context=".fragments.DishDetailView">

    <TextView
        android:id="@+id/textview_view_dishName"
        android:layout_width="300dp"
        android:layout_height="27dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="20dp"
        android:textColor="@color/headercolor"
        android:textSize="@dimen/header_fontsize"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

** content_dish_details_view. xml (макет активности) **

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/nav_graph3" />
</androidx.constraintlayout.widget.ConstraintLayout>

nav-graph. xml

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/nav_graph3"
    app:startDestination="@id/fragment_dishdetailview">

    <fragment
        android:id="@+id/fragment_dishdetailview"
        android:name="com.example.nutritracker.fragments.DishDetailView"
        android:label="DishDetailView"
        tools:layout="@layout/fragment_dishdetailview">
    </fragment>
</navigation>

1 Ответ

1 голос
/ 26 марта 2020

Я думаю, вы должны вернуть rootView по методу onCreateView DishDetailView.

...