在我的MainActivity
我有一个方法showPopUp
,由按钮的监听器调用。所以MainActivity's
布局只包含一个按钮。
ShowPopUp
方法读取按钮状态并返回null pointer expception
。
activity_toggle
是包含toggleButton
的布局。
以下是我的主要活动代码段。
public class MainActivity extends ActionBarActivity {
ToggleButton toggleButton;
String i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showAlertDialog(MainActivity.this);
}
public void showAlertDialog(final Context context){
AlertDialog.Builder ab = new AlertDialog.Builder(context);
View v = LayoutInflater.from(context).inflate(R.layout.activity_toggle,null);
ab.setView(v);
ab.setTitle("toggle mera dil toggle meri jaan");
toggleButton = (ToggleButton)findViewById(R.id.toggleButton1);
toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(toggleButton.isChecked()){
i+=i;
Toast.makeText(MainActivity.this,"Button is on "+i,Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,"Button is off mode",Toast.LENGTH_SHORT).show();
}
}
});
ab.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"ok button pressed",Toast.LENGTH_SHORT).show();
boolean tButton = toggleButton.isChecked();
if(tButton){
Toast.makeText(MainActivity.this,"Button is off on a ",Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
});
ab.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ab.create().show();
}
}
答案 0 :(得分:2)
尝试以下代码。当你从inflater视图中找到视图时,你必须提供View的参考。
toggleButton =(ToggleButton)v.findViewById(R.id.toggleButton1);
View v = LayoutInflater.from(context).inflate(R.layout.activity_toggle,null);
ab.setView(v);
ab.setTitle("toggle mera dil toggle meri jaan");
toggleButton = (ToggleButton)v.findViewById(R.id.toggleButton1);
答案 1 :(得分:0)
使用v
查看从setView
传递AlertDialog
方法的对象,以便从对话框布局访问ToggleButton
:
toggleButton = (ToggleButton)v.findViewById(R.id.toggleButton1);
答案 2 :(得分:0)
toggleButton = (ToggleButton)findViewById(R.id.toggleButton1);
此行在您的活动中查找视图,但此R.id.toggleButton1
控件在对话框中使用的activity_toggle.xml
布局中定义。
试试
toggleButton = (ToggleButton)v.findViewById(R.id.toggleButton1);