Nik*_*iko 19 android android-fragments android-bundle
让我们考虑一下我拥有Fragment A和的情况Fragment B.
B 声明:
public interface MyInterface {
public void onTrigger(int position);
}
Run Code Online (Sandbox Code Playgroud)
A 实现这个接口.
当Fragment B进入堆栈时,我应该如何传递Fragment A它的引用,Bundle以便在需要时A获得onTrigger回调.
我使用的情况是,A具有ListView与项目,并B具有ViewPager与项目.两者都包含相同的项目,当用户从B -> A弹出之前开始B它应该触发回调A以更新它的ListView位置以匹配B寻呼机位置.
谢谢.
Ami*_*pta 23
Passing interface to Fragment
Run Code Online (Sandbox Code Playgroud)
我想你们正在两个人之间进行沟通 Fragment
为此,您可以查看与其他片段进行通信
public class FragmentB extends Fragment{
MyInterface mCallback;
// Container Activity must implement this interface
public interface MyInterface {
public void onTrigger();
}
@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 = (MyInterface ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement MyInterface ");
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
对于 Kotlin 1.0.0-beta-3595
interface SomeCallback {}
class SomeFragment() : Fragment(){
var callback : SomeCallback? = null //some might want late init, but I think this way is safer
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
callback = activity as? SomeCallback //returns null if not type 'SomeCallback'
return inflater!!.inflate(R.layout.frag_some_view, container, false);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18656 次 |
| 最近记录: |