Android - 如何访问 activity 片段中复选框的状态
Android - How to access state of checkboxes in fragments from activity
所以我有一个 class,它有 4 个片段的选项卡式布局,每个片段都有一个复选框列表。我需要将这些复选框的状态保存在 sqlite 数据库中,但我无法使用 activity 中的 findViewById 访问它们(抛出 nullpointerexception)。我该怎么做呢?谢谢!
您无法从您的 activity 访问片段中的视图元素,它根本不是为此创建的。为什么需要这样做?
您可以简单地将复选框的值保存在您的片段代码中,您可以在其中完全访问整个视图。您仍然可以在片段中访问您的 sqlite 数据库,它不必是 activity.
在片段中,您可以覆盖 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;
}
并通过这样做找到元素。
当您第一次添加或替换任何片段时..为它添加一个标签..然后再使用这就是acticity
fragment f1 = getfragmentmanager.findfragmentByTag("tag1");
然后你可以得到并保存
f1.getCheckbox1().ischecked()...
AMD等等...
你可以使用 getFragmentManager.getFragments...
所以我有一个 class,它有 4 个片段的选项卡式布局,每个片段都有一个复选框列表。我需要将这些复选框的状态保存在 sqlite 数据库中,但我无法使用 activity 中的 findViewById 访问它们(抛出 nullpointerexception)。我该怎么做呢?谢谢!
您无法从您的 activity 访问片段中的视图元素,它根本不是为此创建的。为什么需要这样做?
您可以简单地将复选框的值保存在您的片段代码中,您可以在其中完全访问整个视图。您仍然可以在片段中访问您的 sqlite 数据库,它不必是 activity.
在片段中,您可以覆盖 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;
}
并通过这样做找到元素。
当您第一次添加或替换任何片段时..为它添加一个标签..然后再使用这就是acticity
fragment f1 = getfragmentmanager.findfragmentByTag("tag1");
然后你可以得到并保存
f1.getCheckbox1().ischecked()...
AMD等等... 你可以使用 getFragmentManager.getFragments...