[英]How to inflate a layout in method in 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.
}
如何解决这个问题? 因为在活动中,我们只可以在方法中最终结束TextView df =(TextView)findViewById(R.id.df)即可。
您必须在您的片段中创建一个全局View promptView
。
您的代码应如下所示:
private View promptView = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(promptView == null){
promptView = inflater.inflate(R.layout.fragment_messages, container, false);
sendRestoreRequest2();
}
return promptView;
}
public void sendRestoreRequest2() {
final TextView df=(TextView)promptView.findViewById(R.id.df);
}
尝试这个:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View promptView = inflater.inflate(R.layout.fragment_messages, container, false);
sendRestoreRequest2(promptView);
return promptView;
}
public void sendRestoreRequest2(View promptView) {
final TextView df = (TextView) promptView.findViewById(R.id.df);
}
您在ONCREATEVIEW范围之外的方法中没有膨胀的PromptView的范围
你可以做的一件事就是这样
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);
}
解决方案二是这样的
您可以通过覆盖Fragment类中的OnActivityCreated方法来使用简单的getActivty()。findViewbyId来在fragment类中执行findViewbybyid(尽管这是一种被动方法)
对不起,每个人我都是新手。我刚刚找到了解决方案
放在inoncreateview上。 从最终的TextView更改为df =(TextView)promptView.findViewById(R.id.df); 到df = view.findViewById(R.id.df);
而且有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.