【发布时间】:2015-04-13 14:28:06
【问题描述】:
我有一个Fragment 和一个TableLayout。表中的数据来自 SQLite 数据库。 SQLite 数据库由AsyncTask 中的MainActivity 中的RESTful Web 服务填充。 Fragment 必须等待任务完成才能填充表。 Fragment 监听要调用的任务 onPostExecute() 方法。如果是,则调用Fragment 中的方法onLoadAndStoreComplete()。这一切都有效。
我需要查看片段的OnCreateView() 方法之外的TableLayout。如果我能在onLoadAndStoreComplete 中获得片段的视图,那我就可以到达那里。
Same code as here.
我从 MainActivity 获得了 mContext,但没有与之关联的 getView() 方法。
我试过了:
- 创建一个类成员rootView并在onCreateView()中分配,但在onLoadAndStoreComplete()中,它是空的。
- 创建一个类成员 tableLayout 并在 onCreateView() 中分配,但在onLoadAndStoreComplete() 中,它为空。
- 在onLoadAndStoreComplete() 中再次调用this.getView(),但它返回null。
- 在onLoadAndStoreComplete() 内调用充气机,这可行,但后来我不知道在.inflate() 调用中对容器使用什么
不明白为什么onLoadAndStoreComplete()中rootView和tableLayout的类成员值为null
public class MyFragment extends Fragment implements OnLoadAndStoreCompleteListener {
private TableLayout tableLayout;
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mContext = this.getActivity();
rootView = inflater.inflate(R.layout.fragment_permits, container, false); // this works
tableLayout = (TableLayout) rootView.findViewById(R.id.main_table); // and this
...
}
@Override
public void onLoadAndStoreComplete() {
// rootView is null, ie not remembered from OnCreateView
View view = getView(); // null
LayoutInflater inflater = LayoutInflater.from(getActivity());
rootView = inflater.inflate(R.layout.fragment_permits, container, false); // container? don't know what it should be
// tableLayout is null
tableLayout.addView(tableRow, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
...
}
【问题讨论】:
-
什么是
OnLoadAndStoreCompleteListener,何时调用?在 Android API 中找不到这个 -
从未听说过
onLoadAndStoreComplete(),您确定尊重Fragment的生命周期吗?如果你愿意,那么getView()将不会返回null... -
还试图从
Fragment之外的Fragment访问View说Fragment是非常糟糕的设计......我建议你重新考虑你想做的事情并尝试一个更抽象的解决方案。 -
如果你看一下我链接到的上一个问题,你就会明白
onLoadAndStoreCompleteListener()。我不是在尝试访问 Fragment 之外的视图,而是在OnCreateView()之外 -
您的问题需要包含回答问题所需的所有信息。您不能链接到解释此问题中代码的另一个问题。