实际上我有一个 fragment 。`
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View promptView = inflater.inflate(R.layout.fragment_messages, container, false);
sendRestoreRequest2();
return promptView;
}
public void sendRestoreRequest2() {
final TextView df=(TextView)promptView.findViewById(R.id.df);//this will give an error. I dont know how to inflate this one because this is a fragment.
}
如何解决这个问题?因为在 Activity 中我们只需在方法中调用 Final TextView df=(TextView)findViewById(R.id.df) 即可。
最佳答案
您在 ONCREATEVIEW 范围之外的方法中不具有膨胀的 PromptView 范围
one thing that you can do is like this
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View promptView = inflater.inflate(R.layout.fragment_messages, container, false);
sendRestoreRequest2(promptView);
return promptView;
}
public void sendRestoreRequest2(View incomingPromptView) {
// here now you have that promptView in your other method's scope and this should register the TextView in your Fragment
final TextView df=(TextView)incomingPromptView.findViewById(R.id.df);
}
Solution number Two is like this
您可以通过使用简单的 getActivty().findViewbyId 在 Fragment 类中覆盖 OnActivityCreated 方法来在 Fragment 类中执行 findViewbyid (但这是一种被动方法)
关于java - 如何在 fragment 的方法中膨胀布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53221485/