我有一个基本功能 - 启动时 - 将查询蓝牙状态,然后使用textView指示它是否已打开。我正在使用的代码如下:
public class MainActivity extends Activity {
public final int REQUEST_ENABLE_BT = 1;
String btIsOn = "Bluetooth is On";
String btIsOff = "Bluetooth is Off";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set the Textview
final TextView btOn = (TextView)findViewById(R.id.btOnView);
// Create a bluetooth Adapter
BluetoothAdapter btAdapter;
// BT Code
// Check to see if BT Adapter is available
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter.isEnabled()){
btOn.setText(btIsOn);
}
else{
Intent btEnableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(btEnableIntent, REQUEST_ENABLE_BT);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
// Check which request we're responding to
if (requestCode == REQUEST_ENABLE_BT){
// Check to see which option the user selected for BT options
if (resultCode == RESULT_OK){
final TextView btOn = (TextView)findViewById(R.id.btOnView);
btOn.setText(btIsOn);
}
else if (resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Must Enable bluetooth to Use", Toast.LENGTH_SHORT).show();
finish();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
我想知道是否可以只调用textView ONE而不是多次调用textView。那可能吗?如果是这样,如何实施?感谢。
答案 0 :(得分:0)
您可以将TextView添加为类变量:
public class MainActivity extends Activity {
public final int REQUEST_ENABLE_BT = 1;
String btIsOn = "Bluetooth is On";
String btIsOff = "Bluetooth is Off";
TextView btOn;
然后像这样在onCreate中初始化它。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set the Textview
btOn = (TextView)findViewById(R.id.btOnView);
这样,您可以从任何类方法访问TextView,如
btOn.setText("some text");
答案 1 :(得分:0)
您应该全局声明文本视图batOn:
public class MainActivity extends Activity {
public final int REQUEST_ENABLE_BT = 1;
String btIsOn = "Bluetooth is On";
String btIsOff = "Bluetooth is Off";
protected TextView btOn = (TextView) findViewById(R.id.btOnView);
...
}