正如标题所说,我想在一个片段中捕获带有EditText的用户名,并在第二个片段的TextView中显示它。
我正在阅读很多关于它的不同信息,但我不能从中理解,更不用说让它工作了。
这是一个大学项目,目标是制作一个碎片抽屉,就像它是一个服务应用程序。而且,我对Java几乎一无所知,因此我很挣扎。
有人能教我怎么做吗?先谢谢你了。:D
package com.example.devmobile.ui.home;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.devmobile.databinding.FragmentHomeBinding;
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
HomeViewModel homeViewModel =
new ViewModelProvider(this).get(HomeViewModel.class);
binding = FragmentHomeBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textHome;
homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
package com.example.devmobile.ui.catalogo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.devmobile.databinding.FragmentCatalogoBinding;
import com.example.devmobile.ui.home.HomeViewModel;
public class CatalogoFragment extends Fragment {
private FragmentCatalogoBinding binding;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
HomeViewModel catalogoViewModel =
new ViewModelProvider(this).get(HomeViewModel.class);
binding = FragmentCatalogoBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textCatalogo;
catalogoViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
package com.example.devmobile;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class SharedViewModel extends ViewModel {
private final MutableLiveData<String> selectedItem = new MutableLiveData<String>();
public void selectItem(String item) {
selectedItem.setValue(item);
}
public LiveData<String> getSelectedItem() {
return selectedItem;
}
}
1条答案
按热度按时间btqmn9zl1#
使用viewModel,其作用域是activity。