我对如何做到这一点缺乏了解,我见过的大多数例子似乎都不适用于我的情况或绝对让我感到困惑。
我的问题:
我有4个片段,2个用于数据提交,2个用于数据审查和数据计算。我的代码能够从最后两个片段中提取的唯一方法似乎来自主FragmentActivity
。问题是,当Activity通过onCreate方法时,并没有加载我的所有片段,当我尝试声明onClickListener
时,我得到NullPointerException
,因为该页面尚未加载。
现在我确实将setOffscreenPageLimit
设置为3,因此根本不应该成为问题,但我似乎无法弄清楚如何在活动开始时加载页面。
代码:
导致app force关闭的行是btnEnterChemicals
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.swipe_chemicals);
//declarations
...
some declarations
...
//Set up ViewPager and allow app to hold prior pages when off screen
ChemicalsAdapter = new ResultsPagerAdapter(getSupportFragmentManager());
ChemicalsPager = (ViewPager) findViewById(R.id.chemicals_pager);
ChemicalsPager.setAdapter(ChemicalsAdapter);
ChemicalsPager.setOffscreenPageLimit(3);
//When SwipeReviewResults is displayed, fill EditText's with data from other fragments
ChemicalsPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
if (position == 2) {
//Pull values from Chemicals 1
...
some assignments
...
//Pull values from Chemicals 2
...
some assignments
...
//Declare rvw text boxes for Meter Review 1
...
some assignments
...
//Declare rvw text boxes for Meter Review 2
...
some assignments
...
//If data isn't null, perform calculations on client entries
if (data != null)
{
//Do calculations before displaying values in review pages
...
some calculations
...
//Display results
...
display results
...
}
//Copy entered data to Chemicals Review 1
...
display results
...
//Copy entered data to Chemicals Review 2
...
display results
...
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
@Override
public void onPageScrollStateChanged(int arg0) { }
});
//Insert data into database
class insertNew implements Runnable
{
...
data submission
...
}
//Declare and set OnClickListener for Entering Results
final Button btnEnterChemicals = (Button) ChemicalsPager.findViewById(R.id.btnEnterChemicals);
btnEnterChemicals.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//set and encode url for data submission
...
prepare data
...
//Declare and start thread
Thread thrInsertNew = new Thread(new insertNew(url));
thrInsertNew.start();
}
});
提前感谢您的所有帮助!!
答案 0 :(得分:0)
你的onClickListener不应该在包含所述Button的片段的onCreate方法上实现吗?
在我到目前为止看到的示例中,您为要实现的每个选项卡创建了一个Fragment(Java类和XML文件),然后告诉PagerAdapter哪一个对应于哪个位置。 正如你所说,btnEnterChemicals按钮在页面加载之前不存在,因此添加它的onCLickListener的正确方法将在相应片段的onCreate方法中。我不确定这是否能正确解决您的问题。请告诉我。
PS:尝试阅读this以获取有关如何在片段与包含片段的活动之间进行通信的帮助。