【问题标题】:Android - How to access state of checkboxes in fragments from activityAndroid - 如何从活动中访问片段中复选框的状态
【发布时间】:2015-11-21 00:44:01
【问题描述】:

所以我有一个类,它有 4 个片段的选项卡式布局,每个片段都有一个复选框列表。我需要将这些复选框的状态保存在 sqlite 数据库中,但我根本无法使用活动中的 findViewById 访问它们(引发空指针异常)。我该怎么做呢?谢谢!

【问题讨论】:

    标签: android sqlite android-fragments checkbox save


    【解决方案1】:

    当您第一次添加或替换任何片段时..为其添加标签..然后使用这就是活动

    fragment f1 = getfragmentmanager.findfragmentByTag("tag1");
    

    然后就可以获取并保存了

    f1.getCheckbox1().ischecked()... 
    

    amd 等等... 你可以使用 getFragmentManager.getFragments...

    【讨论】:

    • 如果我使用的是浏览器,我该怎么做?我根本不使用事务,所以没有使用添加或替换。
    • 使用片段 f = getFragmentManager().findFragmentByTag("android:switcher:"+R.id.pager+":"+indexPage);
    • 您可能必须使用 getSupportFragmentManager() 而不是 getFragmentManager()... 取决于您如何定义 pagerAdapter
    • 感谢您的回答,但我的问题是我不知道在哪里添加标签...
    • 你不添加标签...viewpager将标签添加到它的片段中
    【解决方案2】:

    您无法从活动中访问片段中的视图元素,它根本不是为此创建的。为什么需要?

    您可以简单地将复选框的值保存在片段代码中,您可以在其中完全访问整个视图。你仍然可以在片段中访问你的 sqlite 数据库,它不必是一个活动。

    【讨论】:

      【解决方案3】:

      在片段中,您可以覆盖 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;
      }
      

      并通过这样做找到元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-15
        • 1970-01-01
        • 1970-01-01
        • 2013-12-24
        • 2018-01-28
        • 2013-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多