[英]How to show a Fragment in a Dialog?
I have created a fragment with some text and an image: 我创建了一个包含一些文本和图像的片段:
public class ContentFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content, container, false);
return view;
}
}
Is there any way to get it to show in a dialog? 有没有办法让它在对话框中显示?
For example: 例如:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Showing a fragment in a dialog");
// Load fragment as dialog content somehow
AlertDialog alert = builder.create();
alert.show();
Every dialog has setView
method which you can create programmatically or inflate, see this example 每个对话框都有
setView
方法,您可以通过编程或膨胀创建该方法,请参阅此示例
You should also consider to use a DialogFragment 您还应该考虑使用DialogFragment
AlertDialog is not supposed to host a fragment. AlertDialog不应该托管片段。
A workaround you can use is to replace dialog UI, which can be achieved by: 您可以使用的解决方法是替换对话框UI,可以通过以下方式实现:
dialog.setContentView(R.layout.fragment_content)
This will just change the dialog view, if you want to bind events or data to the controls inside your fragment, you need to do it after setContentView 这只会更改对话框视图,如果要将事件或数据绑定到片段内的控件,则需要在setContentView之后执行此操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.