开发者

How to use Gallery View in Android, but on another page

开发者 https://www.devze.com 2023-03-17 02:48 出处:网络
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

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:

  1. 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 call finish(), so your welcome activity is not left hanging about.
  2. The problem is that findViewById() acts on whatever is "visible" in the activity right now. Since you did setContentView(main), your Gallery 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号