Android开关小部件强制关闭
尝试在android中创建一个开关,默认状态为ON,OnCheckedChangeListener。但应用程序是强制关闭。怎么了?请帮忙。android开发中的新技术Android开关小部件强制关闭,android,Android,尝试在android中创建一个开关,默认状态为ON,OnCheckedChangeListener。但应用程序是强制关闭。怎么了?请帮忙。android开发中的新技术 package com.tiumca2013.smarthousecontrol; import android.app.Activity; import android.app.Fragment; import android.bluetooth.BluetoothAdapter; import android.content
package com.tiumca2013.smarthousecontrol;
import android.app.Activity;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends Activity{
private Switch switch1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switch1 = (Switch) findViewById(R.id.Switch1);
switch1.setChecked(true); // force close
switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() // force close again
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if(isChecked)
Toast.makeText(getApplicationContext(),"switch 1 ON",Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(),"switch 1 OFF",Toast.LENGTH_SHORT).show();
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
使用Genymotion AVD而不是默认的AVD你有什么版本的android?4.1.2@commonware-我的DDMS logcat显示了数百个错误。在我看来,问题是NullPointException。当我使用try-catch块处理这个问题时,应用程序正在执行,没有任何错误,但再次执行switch1.setChecked(true);它不起作用。