2016-07-25 147 views
0

我想了2天解决这个问题。我做了一个片段,我在其中开启了启用和禁用蓝牙的功能。那么在我的主要活动我写道:Switch findViewById返回null

bluetoothSwitch = (Switch) findViewById(R.id.bluetooth_switch); 
bluetoothSwitch.setOnClickListener(clicked); 

其中点击:

clicked = new ButtonClicked(); 

和:

class ButtonClicked implements AdapterView.OnClickListener 
{ 
    @Override 
    public void onClick(View view) { 
     switch (view.getId()) { 
      case R.id.bluetooth_switch: 
       if (bluetoothAdapter.isEnabled()){ 
        bluetoothAdapter.disable(); 
        Log.d("Log", "Bluetooth is disabled"); 
       } 
       else{ 
        bluetoothAdapter.enable(); 
        Log.d("Log", "Bluetooth is enabled"); 
       } 
       break; 
      case R.id.buttonSearch: 
       arrayListBluetoothDevices.clear(); 
       startSearching(); 
       break; 
      case R.id.discoverable_switch: 
       makeDiscoverable(); 
       break; 
      default: 
       break; 
     } 
    } 
} 

当我运行它的findViewById回空...你有什么想法???

+0

“R.id.bluetooth_switch”在哪里?在你的Activity或Fragment中。因为现在你正在搜索活动。 –

+0

显示您的xml文件以获取您的片段,并且活动帽包含它 – user3793589

回答

1

你试图做的事情不会奏效 - 你的findViewByID寻找活动xml中的视图,但视图(R.id.bluetooth_switch)位于片段的xml中。
请看this SO代码实现的答案。当提供的ID(在你的榜样,这就是所谓的“bluetooth_switch”)在当前容器

0

“findViewById”返回null到我的片段java文件。谢谢。

0

的“资源树”不存在我解决它移动的几行代码