如何让片段将onClickListener结果发送回主活动

时间:2016-10-06 19:42:56

标签: java android android-fragments bluetooth

我有一个Main活动,首次启动时显示一个片段,显示配对蓝牙设备的列表视图。我不想使用ListFragment,因为我想在顶部显示TextView。 我创建了一个onItemClickListener,它使用所选设备的MAC地址和名称设置字符串。这在LOG中显示正常 我想将这些字符串发送回Main活动,然后打开另一个片段,使用这些片段连接到蓝牙设备。

我已经尝试使用所有活动,但想要更改为碎片。

我的主要活动是。

 import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


public class MainActivity extends AppCompatActivity {

    // MAC-address of Bluetooth module (you must edit this line)
    private static String address = "No Device Selected";
    private static String itemName = "No Device Selected";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

}

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        class="com.ming.pondcontroller.AddressFragment"
        android:id="@+id/main_frag"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

我的地址片段

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Set;

public class AddressFragment extends Fragment {

    private static final String TAG = "get address Activity";
    private BluetoothAdapter BA = null;
    private Set<BluetoothDevice> pairedDevices;
    LayoutInflater inflater2;
    ListView lv;
    String address;
    String itemName;
    String itemString;

    public AddressFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        inflater2 = inflater;
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_address, container, false);
    }

    @Override
    public void onStart(){
        super.onStart();
        lv = (ListView)getView().findViewById(R.id.listView);
        BA = BluetoothAdapter.getDefaultAdapter();
        checkBTState();

        // get paired devices
        pairedDevices = BA.getBondedDevices();
        ArrayList list = new ArrayList();
        // get a list of paired devices
        for(BluetoothDevice bt:pairedDevices){
            list.add(bt.getName()+"\n"+bt.getAddress());
        }
        // display the list in the list view
        final ArrayAdapter adapter = new ArrayAdapter(inflater2.getContext(),android.R.layout.simple_list_item_1,list);
        lv.setAdapter(adapter);

        // onItemClick Listener
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView,View view, int position, long l){
                // get the text of the item clicked from position
                itemString = (String)(lv.getItemAtPosition(position));
                // get last 17 characters for MAC address
                address = itemString.substring(itemString.length()-17);
                itemName = itemString.substring(0,itemString.length()-17);
                Log.d(TAG,address);

            }
        }); //end of onClickListener
    }

    private void checkBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on
        // Emulator doesn't support Bluetooth and will return null
        if(BA==null) {
            Log.d("Fatal Error", "Bluetooth not support");
        } else {
            if (BA.isEnabled()) {
                Log.d(TAG, "...Bluetooth ON...");
            } else {
                //Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }
}

及其布局。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorMainBack"
    tools:context="com.ming.pondcontroller.AddressFragment">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/textView"
        android:background="@color/colorPrimary"
        android:textColor="@color/colorWhite"
        android:textSize="20dp"
        android:text="Select Device"/>
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/textView"
        android:background="@color/colorTextBack">
    </ListView> />
</RelativeLayout>

我已经看过很多回调,监听器和接口的例子,但是如果不使用listFragment就无法找到正确的东西。

4 个答案:

答案 0 :(得分:1)

创建一个您的Activity将实现的接口,然后在onAttach()中的片段中将其设置为成员变量:

接口类:

interface BluetoothItemSelected {
    void onBluetoothItemSelected(String itemName, String itemAddress);
}

MainActivity实施:

public class MainActivity extends AppCompatActivity implements BluetoothItemSelected {

    // MAC-address of Bluetooth module (you must edit this line)
    private static String address = "No Device Selected";
    private static String itemName = "No Device Selected";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onBluetoothItemSelected(String itemName, String itemAddress) {
        // TODO do your work here
    }

    // your other Activity code...

}

片段实施:

public class AddressFragment extends Fragment {

    private static final String TAG = "get address Activity";
    private BluetoothAdapter BA = null;
    private Set<BluetoothDevice> pairedDevices;
    LayoutInflater inflater2;
    ListView lv;
    String address;
    String itemName;
    String itemString;

    BluetoothItemListener btItemListener;

    @Override
    public void onAttach(Context activity) {
        if (activity instanceof BluetoothItemListener) {
            btItemListener = (BluetoothItemListener) activity;
        }
    }

    @Override
    public void onDetach() {
        // remove the reference to your Activity
        btItemListener = null;
    }



    @Override
    public void onStart(){
        super.onStart();
        lv = (ListView)getView().findViewById(R.id.listView);
        BA = BluetoothAdapter.getDefaultAdapter();
        checkBTState();

        // get paired devices
        pairedDevices = BA.getBondedDevices();
        ArrayList list = new ArrayList();
        // get a list of paired devices
        for(BluetoothDevice bt:pairedDevices){
            list.add(bt.getName()+"\n"+bt.getAddress());
        }
        // display the list in the list view
        final ArrayAdapter adapter = new ArrayAdapter(inflater2.getContext(),android.R.layout.simple_list_item_1,list);
        lv.setAdapter(adapter);

        // onItemClick Listener
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView,View view, int position, long l){
                // get the text of the item clicked from position
                itemString = (String)(lv.getItemAtPosition(position));
                // get last 17 characters for MAC address
                address = itemString.substring(itemString.length()-17);
                itemName = itemString.substring(0,itemString.length()-17);
                Log.d(TAG,address);
                // call your interface here
                if (btItemListener != null) {
                    btItemListener.onBluetoothItemSelected(itemName, address);
                }
            }
        }); //end of onClickListener
    }

    // your other Fragment code ...
}

答案 1 :(得分:0)

当我需要在我的代码中执行此操作时,我使用LocalBroadcastManager来广播本地消息,其中包含由活动使用BroadcastReceiver获取的意图。

https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html

https://developer.android.com/reference/android/content/BroadcastReceiver.html

我不确定它是否是最好的方式,但它可以很好地用于我的目的。

答案 2 :(得分:0)

我建议你在Activity中实现一个监听器。然后在你的片段中,你可以在onClick

中调用该监听器
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try {
        yourActivityListener = (IActivityListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement IActivityListener");
    }
}

在你的onItemClicked方法中你可以这样调用它

yourActivityListener.onItemClicked();  

这将发送到您的活动,以了解被点击的项目。

答案 3 :(得分:0)

片段:

public static class AddressFragment extends Fragment {

    OnAddressListener mListener;

    // Container Activity must implement this interface
    public interface OnAddressListener {
        public void onAddressChanged(String address);
    }

    // Use : mListener.onAddressChanged(address)

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnAddressListener ) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnAddressListener");
        }
    }
}

的活动:

public class MyActivity extends Activity implements OnAddressListener{


    @Override
    public void onAddressChanged(String address){
           // Set your address
    }

}