Android 为AlertDialog中布局集中的按钮实现onClick()
如果我的按钮已经初始化,我不知道为什么它会得到NullPointerException。 这是我的密码。希望你们能帮忙。谢谢Android 为AlertDialog中布局集中的按钮实现onClick(),android,nullpointerexception,android-alertdialog,buttonclick,Android,Nullpointerexception,Android Alertdialog,Buttonclick,如果我的按钮已经初始化,我不知道为什么它会得到NullPointerException。 这是我的密码。希望你们能帮忙。谢谢 public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case SEARCH: inflater = (LayoutInflater) getSystemService(Contex
public boolean onOptionsItemSelected(MenuItem item)
{ switch (item.getItemId())
{
case SEARCH:
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
AlertDialog.Builder search = new AlertDialog.Builder(this);
search.setTitle(R.string.search);
searchDialog = inflater.inflate(R.layout.search,null);
search.setView(searchDialog);
//The problem should be here
searchButton = (Button) findViewById(R.id.searchButton);
//R.id.searchButton is inside the layout, search.xml
searchButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{ //For testing
Toast.makeText(getApplicationContext(),
"Search was clicked!", Toast.LENGTH_SHORT).show();
}
});
AlertDialog searchDialog = search.create();
searchDialog.show();
return true;
.
.
.
上面的行已更改,要初始化按钮,必须使用视图的引用
public boolean onOptionsItemSelected(MenuItem item)
{ switch (item.getItemId())
{
case SEARCH:
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
AlertDialog.Builder search = new AlertDialog.Builder(YourActivity.this);
search.setTitle(R.string.search);
View view = inflater.inflate(R.layout.search,null);
search.setView(view);
//The problem should be here
searchButton = (Button)view.findViewById(R.id.searchButton);
//R.id.searchButton is inside the layout, search.xml
searchButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{ //For testing
Toast.makeText(getApplicationContext(),
"Search was clicked!", Toast.LENGTH_SHORT).show();
}
});
AlertDialog searchDialog = search.create();
searchDialog.show();
return true;
.
.
.
这很简单,但你的帮助对我来说非常重要。否则,我不知道我需要多少时间来解决这个问题。谢谢
public boolean onOptionsItemSelected(MenuItem item)
{ switch (item.getItemId())
{
case SEARCH:
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
AlertDialog.Builder search = new AlertDialog.Builder(YourActivity.this);
search.setTitle(R.string.search);
View view = inflater.inflate(R.layout.search,null);
search.setView(view);
//The problem should be here
searchButton = (Button)view.findViewById(R.id.searchButton);
//R.id.searchButton is inside the layout, search.xml
searchButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{ //For testing
Toast.makeText(getApplicationContext(),
"Search was clicked!", Toast.LENGTH_SHORT).show();
}
});
AlertDialog searchDialog = search.create();
searchDialog.show();
return true;
.
.
.