如何在 Android 中但在另一个页面上使用图库视图
我在 res/layout 文件夹中有 2 个布局文件:main.xml 和 page2.xml。 在 main.xml 中,我收到了欢迎信息和按钮,该信息开始
setContentView(R.layout.page2);
更改为 page2.xml。
它工作得很好,直到我决定在 page2.xml 中添加图库视图。
当我从开始的 ContentView 设置为 page2 时,如下所示,就可以了。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page2);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
但是当我首先调用 main.xml 以显示可能的起始页面时...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
应用程序返回错误。 我知道问题出在 Context 上
g.setAdapter(new ImageAdapter(this));
,但我完全不知道如何传递正确的上下文或以另一种方式解决它(但我不想将所有布局都放在一个 xml 文件中)。
I've got 2 layout files in res/layout folder: main.xml and page2.xml.
In the main.xml I've got welcome info and button which starts
setContentView(R.layout.page2);
to change to page2.xml.
It worked fine till I decided to add Gallery view in page2.xml.
When I set from begining ContentView to page2 like below it's ok.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page2);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
But when I call main.xml first to show may start page...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
the app returns error.
I know that the problem is with Context in line
g.setAdapter(new ImageAdapter(this));
but I completely don't know how to pass right context or solve it in another way (but I don't want to have all layout in one xml file).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从您的解释中并不完全清楚(日志永远不会造成伤害),但我认为您遇到了空指针异常,因为
gallery
未在您的main.xml
中定义。您的问题有两种解决方案:startActivity()
然后调用finish()
,这样您的欢迎活动就不会悬而未决。setContentView(main)
,因此您的Gallery
将不存在。仅在调用“更改页面”(setContentView(R.layout.page2);
)后才尝试“获取”图库。但是,我强烈建议您选择第一个选项。
It's not entirely clear from your explanation (logs never hurt), but I think you're getting a null pointer exception because
gallery
is not defined in yourmain.xml
. There are two solutions for your problem:startActivity()
and then callfinish()
, so your welcome activity is not left hanging about.findViewById()
acts on whatever is "visible" in the activity right now. Since you didsetContentView(main)
, yourGallery
will not be there. Try "getting" the gallery only after you make the call to "change pages" (setContentView(R.layout.page2);
).However, I would strongly advice you go with the first option.