从片段调用Activity的方法 [英] Call Activity's methods from fragment

查看:110
本文介绍了从片段调用Activity的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简介

我有一个包含一个Activity的蓝牙应用程序,该Activity具有3个可以执行的按钮:

I have a bluetooth app that consists on an Activity which has 3 buttons that do:

  • 设置可见性并创建服务器连接
  • 查找设备并创建客户端连接
  • 发送一些东西

我有以下课程:

  • 主要活动:我拥有所有方法以及按钮监听器
  • 带有线程的3个不同类:ClientConnection,ServerConnection和ConnectedThread

现在,我需要稍微更改一下设计,而不是进行所有这些活动,而要使用ActionBar上的Tab键,我需要创建2个片段:服务器和客户端.

Now I have to change the desing a little bit and instead of having one activity with all this, using Tabs on the ActionBar I need to create 2 fragments: Server and client.

因此,基本上,我必须在Server片段中定义Server和send按钮,在Client片段中定义client按钮,并设置其侦听器.

问题

在每个片段中,当使用一个按钮时,我应该调用其对应的方法,该方法在主Activity中是公开的.我想这样做,而不是复制每个片段中的所有方法和接口,只是为了使其更简单.

From each fragment, when using one button, I should call its corresponding method ubicated in the main Activity. I would like to do it this way, instead of copying all the methods and interfaces in each fragment, just to have it simplier.

我尝试将方法设置为静态,但是方法中有一些无法使用静态引用调用的定义.示例:

I tried setting the methods as static, but there are some definitions inside the methods that can't be called with static references. Example:

public class ServerFragment extends Fragment { 
    //...  
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.server_layout, container, false);

        btnServer = (Button) view.findViewById(R.id.buttonServer);   
        btnServer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickServer();
            }
        });
        //...

_

public class BluetoothActivity extends Activity {
    //...
    public void onClickServer() {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
        startActivityForResult(discoverableIntent, REQUEST_DISCOVERABLE);
    }

如果将onClickServer()设置为静态,则也必须将REQUEST_DISCOVERABLE设置为静态,并且startActivityForResult()不允许我在此处使用静态变量.

If I set onClickServer() as static, I have to set REQUEST_DISCOVERABLE too as static, and the startActivityForResult() doesn't let me use a static variable there.

我该怎么办?

更新-抛出NullpointerException

我创建了一个名为ClickInterface的新类作为建议,并在其中定义了2个接口,一个用于服务器,另一个用于客户端.

I have created new class called ClickInterface as suggestions, and there i have defined the 2 interfaces, one for the server and the other for the client.

不,从片段开始,我试图在onClick方法中调用该方法,但在我对回调方法的调用所在的行中抛出了NPE:

No, from the fragment, I'm trying to call the method in the onClick method, but is throwing an NPE just in the line where i do the call to the callback's method:

public class ServerFragment extends Fragment implements OnClickListener {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.server_layout, container, false);

        btnServer = (Button) view.findViewById(R.id.buttonServer);
        btnServer.setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.buttonServer:
                serverFragCallback.onServer(); //HERE I RECEIVE THE NPE
                break;
        }
    }

这是logcat的输出:

This is the logcat's output:

03-20 16:33:57.581: E/AndroidRuntime(24884): FATAL EXCEPTION: main
03-20 16:33:57.581: E/AndroidRuntime(24884): Process: com.uax.bluetoothconnection, PID: 24884
03-20 16:33:57.581: E/AndroidRuntime(24884): java.lang.NullPointerException
03-20 16:33:57.581: E/AndroidRuntime(24884):    at com.uax.bluetoothconnection.ServerFragment.onClick(ServerFragment.java:43)
03-20 16:33:57.581: E/AndroidRuntime(24884):    at android.view.View.performClick(View.java:4633)
03-20 16:33:57.581: E/AndroidRuntime(24884):    at android.view.View$PerformClick.run(View.java:19330)
03-20 16:33:57.581: E/AndroidRuntime(24884):    at android.os.Handler.handleCallback(Handler.java:733)
03-20 16:33:57.581: E/AndroidRuntime(24884):    at android.os.Handler.dispatchMessage(Handler.java:95)
03-20 16:33:57.581: E/AndroidRuntime(24884):    at android.os.Looper.loop(Looper.java:157)
03-20 16:33:57.581: E/AndroidRuntime(24884):    at android.app.ActivityThread.main(ActivityThread.java:5356)
03-20 16:33:57.581: E/AndroidRuntime(24884):    at java.lang.reflect.Method.invokeNative(Native Method)
03-20 16:33:57.581: E/AndroidRuntime(24884):    at java.lang.reflect.Method.invoke(Method.java:515)
03-20 16:33:57.581: E/AndroidRuntime(24884):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
03-20 16:33:57.581: E/AndroidRuntime(24884):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
03-20 16:33:57.581: E/AndroidRuntime(24884):    at dalvik.system.NativeStart.main(Native Method

推荐答案

您想要的是一个用于从Fragment到Activity进行通信的回调接口. 文档已经提供了一个很好的例子.

What you want is a callback interface for the communication from a Fragment to an Activity. The docs already provide a good example for this.

定义您的Activity实现的接口:

Define an Interface which your Activity implements:

public interface Callback {
    void doSomething();
}

public class YourActivity implements Callback {
    ...
    @Override
    public void doSomething() {
         // your implementation here
    }
}

如果单击其中一个按钮,则在片段中使用此界面.

In your Fragment use this interface if one of the Buttons are clicked.

public class ServerFragment extends Fragment { 

    Callback iCallback;
    ...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            iCallback = (Callback) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.server_layout, container, false);

        btnServer = (Button) view.findViewById(R.id.buttonServer);   
        btnServer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                iCallback.doSomething();
            }
        });
    }
}

使用这种方法,您可以将逻辑留在活动"中,并在片段"中处理UI事件.通过Fragment中的事件,您可以在Activity中调用方法.

With this approach you can leave your logic in the Activity and handle the UI events in the Fragment. Through the events in the Fragment you can invoke the methods in your Activity.

这篇关于从片段调用Activity的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆