findviewbyid在尝试在其他片段中查找NumberPicker时返回null

时间:2016-05-25 16:24:20

标签: java android fragment findviewbyid numberpicker

我的代码在这个项目中是巨大的,所以我会尽力总结我所知道的最新动态。我已经浏览了论坛,并尝试了多条路线来解决这个问题。我希望这是显而易见的,我错过了。

我使用了android studio在新项目向导中创建的tablayout项目,4个选项卡(使每个选项卡都有自己的片段)。

在片段1上,我onclicklistener尝试更改片段2上numberpicker的值。我的问题是findviewbyid上的numberpicker一直在回来空值。我已经为findviewbyid尝试了多种格式,并且它一直返回null。

基本上我正在尝试访问另一个片段上的对象而findviewbyid没有找到该对象。

otherpck = (NumberPicker) getActivity().findViewById(R.id.pckOther);
otherpck.setValue(5);

如果我在onclicklistener中为片段1上的按钮运行上述代码,试图在片段2上找到pckOther,则会将otherpck设置为null。

所有碎片都已膨胀。我可以单击所有选项卡,然后单击fragment1上的按钮,仍然可以为空。

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

您不应该直接从另一个活动/片段访问片段的视图,因为android管理您的活动并按需暂停/停止它们。所以想象你在活动B中你去吃午饭然后你回来30分钟后你的活动B将被恢复但是很有可能机器人杀死你的活动A所以当你试图访问它的视图时它将返回null。

相反,您可以使用其中一个选项。

使用Bundle。 http://developer.android.com/reference/android/os/Bundle.html

1)使用意图中的Bundle:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);

2)创建一个新的Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);

3)使用Intent的putExtra()快捷方法

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);

然后,在启动的Activity中,您将通过以下方式阅读它们:

String value = getIntent().getExtras().getString(key);

这是正确的方法。另一种方式是SharedPreferences。 http://developer.android.com/training/basics/data-storage/shared-preferences.html

答案 1 :(得分:0)

如果没有创建并附加到活动,则有一些问题您无法要求查看。如您所说,您正在使用片段,如果该片段尚未附加到您的活动,则您的活动无法访问该视图。

答案 2 :(得分:0)

替换这一行:

otherpck = (NumberPicker) getActivity().findViewById(R.id.pckOther);

这一行:

otherpck = (NumberPicker) findViewById(R.id.pckOther);
相关问题