我想在Fragment类中使用变量到Home类



我想在片段类中使用postRecyclerView变量到home类..

因为我想在添加post时滚动位置。但在home类中,我需要定义recyclerview。所以我打算从片段类中使用recyclerview变量。

这是主类代码

myRef.setValue(post).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
popupClickProgress.setVisibility(View.INVISIBLE);
popupAddBtn.setVisibility(View.VISIBLE);
// illegal 오류 해결 수정
if(popAddPost!=null&&popAddPost.isShowing()){
popAddPost.dismiss();
}
FragmentManager fm = getSupportFragmentManager();
HomeFragment frag1 = (HomeFragment)fm.findFragmentById(R.id.postRecylerView);
frag1.

}
});

和片段类

public class HomeFragment extends Fragment {

private OnFragmentInteractionListener mListener;
private int position;
private int ant;

RecyclerView postRecyclerView ;
PostAdapter postAdapter;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
List<Post> postList;

public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
LinearLayoutManager lin = new LinearLayoutManager(getActivity());
lin.setStackFromEnd(true);
lin.setReverseLayout(true);
View fragmentView = inflater.inflate(R.layout.fragment_home, container, false);
postRecyclerView = fragmentView.findViewById(R.id.postRV);
postRecyclerView.setLayoutManager(lin);
postRecyclerView.setHasFixedSize(true);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Posts");
return fragmentView;
}

我不知道为什么我不能接近postRecyclerView变量??

你能给我提个建议吗?

所以从我的理解,你正试图传递该变量的值(from Home.java)到一个片段内部的回收器视图?就是这样吗?

你要做的是在类之间传递数据。我对Java有点生疏了,所以这可能不是最好的方法,但请尝试一下,然后给我答复。

class yourClass {
private myClassA classAInstance;
public yourClass(myClassA a)
{
classAInstance = a;
}
void I_AM_a_button_press()  // function
{
classAInstance.printVariable();
}
}

我也建议你看看这篇关于这件事的博客文章,它会对你有很大的帮助。祝你好运。

http://www.thetopsites.net/article/54159971.shtml

最新更新