onClick调用Activity内部的片段

我现在正在封装一个片段,并遇到一个难以谷歌的问题。 在我的片段里面有一些带有onClick属性的button,但是它们在Activity上被调用,而在android系统上被调用 – 这使得封装有点笨拙。 有没有办法从onClick调用reflection的东西来调用片段? 我目前看到的唯一解决scheme是不使用xml中的onClick,并通过代码设置片段内的点击侦听器。

我和一些google @ @ adl2011交谈过 – 他们认识到这个问题,未来可能会有一些解决办法。 在此之前 – 应该在片段中使用.setOnClick。

问题是,当布局充气,它仍然是托pipe活动,接受button点击,而不是个别碎片。

我更喜欢使用以下解决scheme来处理onClick事件。 这也适用于Activity和Fragments。

public class StartFragment extends Fragment implements OnClickListener{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_start, container, false); Button b = (Button) v.findViewById(R.id.StartButton); b.setOnClickListener(this); return v; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.StartButton: ... break; } } } 

然后问题就消失了。

这个对我有用

添加导入:

  import android.view.View.OnClickListener; 

Fragment.java

  ... @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = (ViewGroup) inflater.inflate(R.layout.fragment, container, false); Button mButton = (Button) rootView.findViewById(R.id.button); mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { } }); return rootView; } 

问题:

1. XML onClick属性将调用活动的公共方法。

2.片段的公开方法不被调用。

3.片段的可重用性。

解:

片段的布局中添加这个视图。

 android:onClick="onFragmentViewClick" 

在每个活动中 ,片段可能属于..

 public void onFragmentViewClick(View v) { Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container); if (fragment != null && fragment.isVisible()) { if (fragment instanceof SomeFragment) { ((SomeFragment) fragment).onViewClicked(v); } } } 

Fragment中包含这个方法..

 public void onViewClicked(View v) { switch (v.getId()) { case R.id.view_id: Log.e("onViewClicked", "yehhh!!"); break; } } 

您可以让活动中正在调用的侦听器将该调用转发到片段中的侦听器。 你应该引用FragmentActivity中的片段来传递呼叫。 你将不得不施放调用方法或让你的片段实现你定义的接口。 我知道这不是最好的解决scheme,但它会工作。 如果需要,也可以使用button的标签指定要调用的方法名称。 希望这个对你有帮助。

尝试这个…

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.activity_ipadditional_users, container, false); FloatingActionButton button7 = (FloatingActionButton) rootView.findViewById(R.id.fab_ip_additional_user); button7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), IPAdditionalUsersEdit.class); startActivity(intent); } }); return rootView;