我在我的活动中宣布我的片段是这样的:
private boolean profileDetailsCreated = false;
private boolean trackChanged = false;
private int trackValue = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.project_profile_details, container, false);
profileDetailsCreated = true;
if(trackChanged) {
Log.d(Constants.DEBUG, "THE TRACK CHANGED HAS OCCURED BEFORE PROFILE DETAILS CREATED");
setTrackCount(trackValue);
}
return rootView;
}
public void setTrackCount(int value) {
Log.d(Constants.DEBUG, "THE value for set track count is " + value);
if(profileDetailsCreated) {
Log.d(Constants.DEBUG, "THE PROFILE DETAIL IS CREATED CHANGE SHOULD HAPPEN");
dbProject.setTrackedCount(trackC + value);
db.projectUpdateTrack(dbProject);
trackC = dbProject.getTrackedCount();
showTrackBackgroundText();
} else {
Log.d(Constants.DEBUG, "THE PROFILE DETAIL IS NOT CREATED STORE THE DATA " + value);
trackValue = value;
trackChanged = true;
}
}
现在,在我所做的一切活动结束时,我在一个按钮上调用一个setOnClickListener,如果片段完全加载,它就可以正常工作 - 因为单击该按钮会告诉一个片段不在视图中更新其视图的一部分。但是,如果我立即单击该按钮,那么它将使应用程序崩溃,因为片段尚未完全加载并且出现空错误。片段完全加载后如何启用按钮,或者当片段完全加载时如何设置OnTheOnClicklistener?
修改
为了让事情更清楚 - 我有一个跟随按钮,显示在两个片段上。一个在片段上它只显示另一个片段上的图片,它显示了该人的详细信息。如果用户单击任一片段上的跟随按钮,则必须更新详细信息片段上的计数(关注者计数+ 1)。
更新:
这是你的答案adelphus的尝试 - 这是我的片段类:
Form1 with
答案 0 :(得分:1)
在这种情况下,您应该在OnClickListener
生命周期方法中设置onActivityCreated
:
private Button yourButton;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View rooView = getView();
yourButton = (Button) rooView.findViewById(R.id.your_button);
//then you can set the
yourButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//do stuff here!
}
});
}
答案 1 :(得分:1)
根据您的意见,我会尝试让我的解释更加清晰。很难想象出您所面临的问题,因为您没有描述更新的内容。
这是我的建议(在伪代码中):
class MainActivity extends Activity {
public void onCreate(..) {
...
// assuming the button is part of the activity view
btn.setOnClickListener((View) => {
Info info = getInfoNeededForUpdate();
fragment1.update(info);
fragment2.update(info);
});
}
}
// Frag2 is the same logic as Frag1
class Frag1 extends Fragment {
boolean mCreated;
Info mPendingInfo;
public void onCreateView(...) {
// inflate view, blah
...
// mark us as created
mCreated = true
// apply any pending updates
if (mPendingInfo != null)
this.update(info);
}
public void update(Info info) {
// first check if we've been created
if (this.mCreated) {
// yep - go ahead and apply the updates to the views
...
} else {
// nope - save it for later (update will be applied in onCreateView)
this.mPendingInfo = info;
}
}
}
希望您可以从中看到,将更新应用于片段并不重要 - 视图将立即更新(如果已经调用片段onCreateView()
)或者在应用更新之前等待onCreateView()
被调用。