我是开发Android的新手,现在我在Fragments之间调用方法时遇到了问题。让我来形容一下,我希望每个人都能帮我解决它。
片段A
public class A extends Fragment implements OnItemClickListener {
.........
.........
.........
public void showContent(int pSelectedIndex, int pSelectedSubIndex) {
// Create fragment and give it an argument specifying the article it
RelativeLayout thisTopLayout = (RelativeLayout)getActivity().findViewById(R.id.directoryTopRelativeLayout);
thisTopLayout.setVisibility(LinearLayout.GONE);
RelativeLayout thisBodyLayout = (RelativeLayout)getActivity().findViewById(R.id.directoryBodyRelativeLayout);
thisBodyLayout.setVisibility(LinearLayout.GONE);
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
if (pSelectedIndex == 1) {
BusinessView thisItem = new BusinessView();
transaction.replace(R.id.directoryLayout, thisItem);
thisItem.DetectContentType(pSelectedSubIndex, this.getActivity());
}
}
}
片段B
public class B extends Fragment implements OnItemClickListener {
@SuppressWarnings("deprecation")
public void DetectContentType(int selectedType, Activity pActivity){
if (selectedType != 1) {
AlertDialog alertDialog = new AlertDialog.Builder(pActivity)
.create();
alertDialog.setTitle("EXAMPLE");
alertDialog
.setMessage("SHOW MESSAGE");
alertDialog.setButton("YES", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int which) {
// here you can add functions
}
});
alertDialog.setButton2("NO", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int which) {
// here you can add functions
}
});
alertDialog.show();
} else {
showContent(selectedType);
}
}
public void showContent(int pSelectedIndex) {
// Create fragment and give it an argument specifying the article it
RelativeLayout thisTopLayout = (RelativeLayout) this.getActivity().findViewById(R.id.businessTopRelativeLayout);
thisTopLayout.setVisibility(LinearLayout.GONE);
RelativeLayout thisBodyLayout = (RelativeLayout) this.getActivity()
.findViewById(R.id.businessBodyRelativeLayout);
thisBodyLayout.setVisibility(LinearLayout.GONE);
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
BusinessItemView thisItem = new BusinessItemView(pSelectedIndex);
transaction.replace(R.id.businessLayout, thisItem);
// Commit the transaction
transaction.commit();
}
}
这是我的类,当我在Fragment A中时,我想在片段B中执行方法“showContent”,但我可以只显示Alert,但方法“showContent”总是会出现崩溃错误。
请告诉我你这个案子的想法。 非常感谢。
答案 0 :(得分:2)
在片段A中,您需要稍微更改方法调用;
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
if (pSelectedIndex == 1) {
BusinessView thisItem = new BusinessView();
transaction.replace(R.id.directoryLayout, thisItem);
transaction.commit();
thisItem.DetectContentType(pSelectedSubIndex, this.getActivity());
}
片段B上的DetectContentType方法无法对AlertDialogs做任何事情,直到片段通过事务附加,通过调用commit。
同样在您的特定情况下,尽管提供了用于AlertDialog构建器的活动,这对您的情况应该没问题,但是如果提交您正在传递的事务pSelectedSubIndex
,则不需要,但不知道从你的例子中你可能会在片段B上点击showContent()
,这肯定会失败,因为在你开始片段生命周期之前你无法附加视图。