【发布时间】:2015-11-21 00:44:01
【问题描述】:
所以我有一个类,它有 4 个片段的选项卡式布局,每个片段都有一个复选框列表。我需要将这些复选框的状态保存在 sqlite 数据库中,但我根本无法使用活动中的 findViewById 访问它们(引发空指针异常)。我该怎么做呢?谢谢!
【问题讨论】:
标签: android sqlite android-fragments checkbox save
所以我有一个类,它有 4 个片段的选项卡式布局,每个片段都有一个复选框列表。我需要将这些复选框的状态保存在 sqlite 数据库中,但我根本无法使用活动中的 findViewById 访问它们(引发空指针异常)。我该怎么做呢?谢谢!
【问题讨论】:
标签: android sqlite android-fragments checkbox save
当您第一次添加或替换任何片段时..为其添加标签..然后使用这就是活动
fragment f1 = getfragmentmanager.findfragmentByTag("tag1");
然后就可以获取并保存了
f1.getCheckbox1().ischecked()...
amd 等等... 你可以使用 getFragmentManager.getFragments...
【讨论】:
您无法从活动中访问片段中的视图元素,它根本不是为此创建的。为什么需要?
您可以简单地将复选框的值保存在片段代码中,您可以在其中完全访问整个视图。你仍然可以在片段中访问你的 sqlite 数据库,它不必是一个活动。
【讨论】:
在片段中,您可以覆盖 onCreateView 并膨胀视图。 http://developer.android.com/training/basics/fragments/creating.html
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.article_view, container, false);
TextView textView = (TextView) v.findViewById(R.id.testelement);
return v;
}
并通过这样做找到元素。
【讨论】: