我的目标是从Fragment访问MainActivity的ProgressBar和TextView。但是,我收到以下错误:
尝试调用虚方法'void 空对象上的android.widget.ProgressBar.setVisibility(int)' 参考
activity_main.xml中
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:orientation="vertical"
android:layout_gravity="center">
<ProgressBar
android:id="@+id/pbLoading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
android:layout_gravity="center"
android:visibility="visible"/>
<TextView
android:id="@+id/tvLoading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="@dimen/dimension_8dp"
android:fontFamily="@font/robotomedium"
android:textSize="16sp"
android:visibility="visible"
android:text="@string/loading_text"/>
</LinearLayout>
SampleFragment.java
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
fragmentDataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_currency_list, container, false);
return Objects.requireNonNull(fragmentDataBinding).getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
mPbLoading = fragmentDataBinding.getRoot().findViewById(R.id.pbLoading);
mPbLoading.setVisibility(View.GONE);
}
篡改了很多帖子,文章却无法实现。提前谢谢。
最佳,
答案 0 :(得分:1)
选项1
在活动中将进度条设为静态 然后从片段中访问 -
if(MainActivity.progressbar!=null){
MainActivity.progressbar.setVisibility(View.Gone);
//or whatever do you want
}
选项2
((YourActivityClassName)getActivity()).yourPublicMethod();
答案 1 :(得分:1)
fragmentDataBinding.getRoot()。findViewById(R.id.pbLoading);
因为fragmentDataBinding.getRoot()为您提供了片段布局,但没有活动布局!
此外,将视图保存在静态引用中非常糟糕,并且会导致内存泄漏!
解决方案1 :
3.1在“活动”中,您可以定义类似的方法
public void changeProgressBarVisibility(int status) {
activityBinding.pbLoading.setVisibility(status);
}
在您可以使用的片段中3.2
((YourActivityClassName) getActivity()).changeProgressBarVisibility(View.VISIBLE); // View.GONE
使用ViewModel:
4.1在您的活动中
ActivityBinding binding;
MyViewModel viewModel;
// in onCreate()
binding = DataBindingUtil.setContentView(this, R.layout.activity_layout);
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
viewModel.setActivityBinding(binding);
4.2在ViewModel中
private ActivityBinding binding;
public void setActivityBinding(ActivityBinding binding) {
this.binding = binding;
}
public void changeProgressBarVisibility(int status){
binding.pbLoading.setVisibility(status);
}
片段中的4.3
private MyViewModel viewModel;
// in onActivityCreated() after onCreateView():
viewModel = new ViewModelProvider(getActivity()).get(MyViewModel.class); // Do not use "this" instead of "getActivity()"
// in some method
viewModel.changeProgressBarVisibility(View.VISIBLE); // View.GONE