根据父活动在片段中调用不同的方法
Posted
技术标签:
【中文标题】根据父活动在片段中调用不同的方法【英文标题】:Call different method in fragment based on parent activity 【发布时间】:2021-12-20 08:56:41 【问题描述】:我在我的应用程序中有一个包含一些输入字段的片段,我在两个不同的活动中显示这个片段,在这两种情况下,布局都是相同的,但我需要根据谁是父活动执行不同的操作.
我将尝试使用以下代码更好地解释我的问题和我正在使用的解决方案:
活动A
public class ActivityA extends AppCompatActivity
private NavController navController;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.ActivityA);
navController = Navigation.findNavController(this,R.id.graphA);
initView();
public void nextFragment(int actionID, Bundle bundle)
btn.setOnClickListener(v->
navController.navigate(from_activityA_toFragment, bundle);
);
活动B
public class ActivityB extends AppCompatActivity
private NavController navController;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.ActivityA);
navController = Navigation.findNavController(this,R.id.graphB);
initView();
public void nextFragment(int actionID, Bundle bundle)
btn.setOnClickListener(v->
navController.navigate(from_activityB_toFragment, bundle);
);
现在在我的片段类中,我有这样的东西
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
View rootview = inflater.inflate(R.layout.fragemnt, container, false);
if(getActivity().getClass().equals(ActivityA.class))
//Do things of activityA
else if(getActivity().getClass().equals(ActivityB.class)))
//Do things of activityB
return rootview;
现在这段代码可以工作,但似乎不是归档我的目标的最佳方式,所以有人有什么建议吗?谢谢
【问题讨论】:
【参考方案1】:你可以查看实例
在Java中你可以使用instaceof
if(getActivity() instanceof ActivityA)
// Do things of activityA
else if(getActivity() instanceof ActivityB)
// Do things of activityB
对于 Kotlin
if(getActivity() is ActivityA)
// Do things of activityA
else if(getActivity() is ActivityB)
// Do things of activityB
【讨论】:
【参考方案2】:正确的做法是在Fragment中定义一个接口,让Activity实现接口,让Fragment把Activity投到接口上。
以下指南对其进行了描述:https://web.archive.org/web/20180405192526/https://developer.android.com/training/basics/fragments/communicating.html
public class HeadlinesFragment extends Fragment
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener
public void onArticleSelected(int position);
@Override
public void onAttach(Activity activity)
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try
mCallback = (OnHeadlineSelectedListener) activity;
catch (ClassCastException e)
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
...
【讨论】:
以上是关于根据父活动在片段中调用不同的方法的主要内容,如果未能解决你的问题,请参考以下文章