无法从 onOptionsItemSelected 中使用 LayoutInflater
我正在尝试通过选项菜单项来扩展布局。 我尝试使用的代码如下,
public class Test01 extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
...
setContentView(R.Layout.main);
...
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
theMenu=menu;
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.main_optmenu, theMenu);
return(super.onCreateOptionsMenu(menu));
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.item1:
LayoutInflater li=(LayoutInflater)getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
li.inflate(R.layout.mylayout,this,true);
case R.id.item2:
...
default:
....
}
}
}
我收到 2 个错误 - “getContext() 未定义”,因此在搜索后我将其更改为 getApplicationContext() 然后我能够获取 LAYOUT_INFLATER_SERVICE。
但是在第二行中,不接受 ViewGroup 参数。 错误信息是 “LayoutInflater 类型中的方法 inflate(int, ViewGroup, boolean) 不适用于参数 (int, test01, boolean)”
看来我没有为参数提供正确的值, 菜单本身工作正常,因为我可以用 setContentView 替换 LayoutInflater
我非常感谢您的帮助, “谢谢
I am trying to inflate a layout through an options menu item.
code i tried to use is as follows
public class Test01 extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
...
setContentView(R.Layout.main);
...
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
theMenu=menu;
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.main_optmenu, theMenu);
return(super.onCreateOptionsMenu(menu));
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.item1:
LayoutInflater li=(LayoutInflater)getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
li.inflate(R.layout.mylayout,this,true);
case R.id.item2:
...
default:
....
}
}
}
i get 2 errors - "getContext() is undefined" so after searching i changed it to getApplicationContext() then i am able to obtain LAYOUT_INFLATER_SERVICE.
But then in the second line the ViewGroup parameter is not accepted..
Error message is
"The method inflate(int, ViewGroup, boolean) in the type LayoutInflater is not applicable for the arguments (int, test01, boolean)"
It seems i am not providing the correct values for the parameters,
The menu itself works fine as i am able to replace LayoutInflater with setContentView
I would really appreciate your help ,
"thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
替换
将li.inflate(R.layout.mylayout,this,true);
为
Replace
li.inflate(R.layout.mylayout,this,true);
with
请在程序中使用 base.oncreate(savedInstanceState) 代替 super.oncreate(savedInstanceState)...并且您还需要在方法中定义 getcontext ()...
Please use base.oncreate(savedInstanceState) instead for super.oncreate(savedInstanceState) in your program...and also you need to define getcontext () in your method...