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开发者_StackOverflow社区 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).
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 your main.xml
. There are two solutions for your problem:
- Split your two "pages" into two activities. This is a much more natural way of dealing with things. Try rotating your phone/emulator and you'll see what I mean. When the user clicks on the button or whatever, call
startActivity()
and then callfinish()
, so your welcome activity is not left hanging about. - The problem is that
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.
精彩评论