android如何用外部类,android如何知道onCreateView是从外部类调用的?_android-fragments_开发99编程知识库...

本文介绍了如何通过创建一个接口并在Fragment的宿主Activity中实现该接口,来确保在Fragment的onCreateView方法被调用时,能够通知到外部类。主要步骤包括在Fragment中定义回调接口,Activity中实现接口并覆盖回调方法,在onAttach中检查Activity是否实现了回调,最后在onCreateView中触发回调。这种方法可用于传递数据或通知其他类onCreateView的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我如何知道onCreateView是從外部類調用的?

你需要在 fragment 內部創建介面,並在容器 Activity ( 假設是 MainActivity ) 中實現它。

1 在你的fragment 中創建一個介面://Container activity must implement this interface

public interface OnCreateViewCalledListener {

void OnCreateViewCalled(String someData);

}

2.在容器 Activity ( 假設它是 MainActivity ) 內實現介面,並調用它的方法:public class MainActivity extends AppCompatActivity implements

YourFragment.OnCreateViewCalledListener {

...

@Override

public void OnCreateViewCalled(String someData) {

Toast.makeText(MainActivity.this,"OnCreateView was called and passed" + someData)

}

3 然後你需要檢查MainActivity是否實現了介面回調( 這裡步驟對於使它的正常工作非常重要)://Using onAttach method to check that activity has implemented callbacks

@Override

public void onAttach(Activity activity) {

super.onAttach(activity);

//Make sure that container activity has implemented

//the callback interface. If not, it throws an exception

try {

mCallback = (OnCreateViewCalledListener) activity;

} catch (ClassCastException e) {

throw new ClassCastException(activity.toString()

+" must implement OnCreateViewCalledListener");

}

}

4,最後你需要在onCreateView中觸發回調:@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

mCallback.OnCreateViewCalled("Some useful data");

. . .

}

就是這樣!

編輯:

讓其他類知道onCreateView被調用,請使用MainActivity中的onCreateViewCalled() 回調( 比如 。 使用另一個介面在其他類中觸發回調) 。 也不是強制將數據傳遞到 OnCreateViewCalled ( )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值