我需要在片段内操作我的按钮等,但是 findViewById 方法无法识别。此外,甚至无法设置警报对话框,因为无法识别方法。
如果我添加 getActivity() 或 getActivity().getApplicationContext() 它适用于片段绑定的活动。
实现我的对象并在片段内对它们进行操作的正确方法是什么?
我需要在片段内操作我的按钮等,但是 findViewById 方法无法识别。此外,甚至无法设置警报对话框,因为无法识别方法。
如果我添加 getActivity() 或 getActivity().getApplicationContext() 它适用于片段绑定的活动。
实现我的对象并在片段内对它们进行操作的正确方法是什么?
该方法是从类findViewById
继承的。Activity
在片段中,您可以在特定View
对象上调用此方法。在大多数情况下,您将在膨胀视图上调用它。请记住,这findViewById
是一个缓慢的操作!将您的视图的引用保留为活动成员始终是一个好习惯。还要在最具体的View
对象上调用此方法 - 如果您想从放置在较大容器中的容器中获取视图,请在较小的容器上调用该方法 - 它更快。:)
例如
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.list_view_fragment, container, false);
listView = (ListView)v.findViewById(R.id.listView);
ImageButton imageBtn = (ImageButton)v.findViewById(R.id.imageButton);
imageBtn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
Builder MyAlertDialog = new AlertDialog.Builder(getActivity());
MyAlertDialog.setTitle("Title");
MyAlertDialog.setMessage("Message");
DialogInterface.OnClickListener deleteClick = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
//your code
}
};
MyAlertDialog.setPositiveButton("First",deleteClick );
MyAlertDialog.setNeutralButton("Second",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which){
//second
}
});
MyAlertDialog.setNegativeButton("Last",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
return;
}
});
MyAlertDialog.show();
}
});
return v;
}
对于 Fragment,您应该覆盖 onCreateView 方法并膨胀您想要的视图
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.your_fragment_layout, container, false);
progressBar = (ProgressBar)root.findViewById(R.id.progress_bar);
}