IllegalStateException:找不到父或祖先的方法上下文中的android:onClick属性在视图类上定义

时间:2017-04-19 16:45:01

标签: java android button onclick illegalstateexception

当我点击ID为#34; btnDiscoverable_on_off"的按钮时和" lvNewDevices"我收到这个错误:

 java.lang.IllegalStateException: Could not find method btnDiscover(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btnFindUnpairedDevices'

这是代码:

import android.Manifest;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
public class PrimoFragment extends Fragment implements 
AdapterView.OnItemClickListener {

View myView;

private static final String TAG = "MainActivity";

BluetoothAdapter mBluetoothAdapter;
Button btnEnableDisable_Discoverable;

public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();

public DeviceListAdapter mDeviceListAdapter;

ListView lvNewDevices;



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



    Button btnONOFF = (Button) myView.findViewById(R.id.btnONOFF);
    btnEnableDisable_Discoverable = (Button) myView.findViewById(R.id.btnDiscoverable_on_off);
    lvNewDevices = (ListView) myView.findViewById(R.id.lvNewDevices);
    mBTDevices = new ArrayList<>();

    //Broadcasts when bond state changes (ie:pairing)
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    getActivity().registerReceiver(mBroadcastReceiver4, filter);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    lvNewDevices.setOnItemClickListener(PrimoFragment.this);


    btnONOFF.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d(TAG, "onClick: enabling/disabling bluetooth.");
            enableDisableBT();
        }
    });



    return myView;
}



public void enableDisableBT(){
    if(mBluetoothAdapter == null){
        Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
    }
    if(!mBluetoothAdapter.isEnabled()){
        Log.d(TAG, "enableDisableBT: enabling BT.");
        Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivity(enableBTIntent);

        IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        getActivity().registerReceiver(mBroadcastReceiver1, BTIntent);
    }
    if(mBluetoothAdapter.isEnabled()){
        Log.d(TAG, "enableDisableBT: disabling BT.");
        mBluetoothAdapter.disable();

        IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        getActivity().registerReceiver(mBroadcastReceiver1, BTIntent);
    }

}


public void btnEnableDisable_Discoverable(View view) {
    Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");

    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
    startActivity(discoverableIntent);

    IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
    getActivity().registerReceiver(mBroadcastReceiver2,intentFilter);

}

public void btnDiscover(View view) {
    Log.d(TAG, "btnDiscover: Looking for unpaired devices.");

    if(mBluetoothAdapter.isDiscovering()){
        mBluetoothAdapter.cancelDiscovery();
        Log.d(TAG, "btnDiscover: Canceling discovery.");

        //check BT permissions in manifest
        checkBTPermissions();

        mBluetoothAdapter.startDiscovery();
        IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        getActivity().registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
    }
    if(!mBluetoothAdapter.isDiscovering()){

        //check BT permissions in manifest
        checkBTPermissions();

        mBluetoothAdapter.startDiscovery();
        IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        getActivity().registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
    }
}

/**
 * This method is required for all devices running API23+
 * Android must programmatically check the permissions for bluetooth. Putting the proper permissions
 * in the manifest is not enough.
 *
 * NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
 */
private void checkBTPermissions() {
    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
        int permissionCheck = this.getActivity().checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
        permissionCheck += this.getActivity().checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
        if (permissionCheck != 0) {

            this.getActivity().requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
        }
    }else{
        Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
    }
}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    //first cancel discovery because its very memory intensive.
    mBluetoothAdapter.cancelDiscovery();

    Log.d(TAG, "onItemClick: You Clicked on a device.");
    String deviceName = mBTDevices.get(i).getName();
    String deviceAddress = mBTDevices.get(i).getAddress();

    Log.d(TAG, "onItemClick: deviceName = " + deviceName);
    Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);

    //create the bond.
    //NOTE: Requires API 17+? I think this is JellyBean
    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
        Log.d(TAG, "Trying to pair with " + deviceName);
        mBTDevices.get(i).createBond();
    }
}

}

XML代码primo_fragment:

<?xml version="1.0" encoding="utf-8"?>
<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">


<Button
    android:text="ON/OFF"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btnONOFF"
    android:layout_alignParentEnd="true" />

<Button
    android:text="Enable Discoverable"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btnDiscoverable_on_off"
    android:onClick="btnEnableDisable_Discoverable"

    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btnFindUnpairedDevices"
    android:text="Discover"
    android:onClick="btnDiscover" />

<ListView
    android:layout_width="wrap_content"
    android:layout_height="150dp"
    android:id="@+id/lvNewDevices"
    android:layout_marginTop="62dp"
    android:layout_alignParentStart="true" />

</RelativeLayout>

device_adapter_view

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

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tvDeviceName"
    android:textSize="15sp"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tvDeviceAddress"
    android:textSize="15sp"/>


</LinearLayout>

这两个按钮有什么问题?我无法找到问题

1 个答案:

答案 0 :(得分:1)

请按照this结构使用片段的xml onClick 属性。希望你的问题能得到解决。