Getting View resources from class

Quickly share your Android Code Snippets here...

Getting View resources from class

Postby jsucamel » Mon Jun 14, 2010 11:18 pm

Hey guys,

I've got a main class and a second class that handles an object within the main class. The second class needs to manipulate the layout of the main class (changing background images of objects), but the findViewById() function is returning null every time. The second class isn't a new Activity (at least, I don't think it should be), so I'm pretty sure I don't want to call setContentView(R.layout.main) in the second class, since the main class is an activity with that View.

Here's what I have:

Code: Select all
public class MainClass extends Activity {

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        SubClass item = new SubClass(this);
   }

}


And then the other class is:

Code: Select all
public class Dice extends View  {
        public Dice(Context context){
      super(context);
      img1 = (ImageView)findViewById(R.id.img1);
   }
}


There is more to the code, but these are the relevant bits. The img1 is always null, no matter what I do.

Ideas?
jsucamel
Freshman
Freshman
 
Posts: 2
Joined: Mon Dec 22, 2008 6:44 pm

Top

Re: Getting View resources from class

Postby capnKate » Tue Jun 22, 2010 5:06 pm

I'm fairly new to droid, so I can't promise I'll be tons of help.

Essentially, what I think is going on is that you Dice class has no reference to your main.xml. It's not enough for the two files to be in the same package, the class has to call the xml. I'm unaware of a way to reference a layout with out calling setContentView(R.layout.main); but that doesn't mean that one doesn't exist.

My only suggestions would be to either pass changes you want to make back to your MainClass and actually do them there, or call your images that are instantiated in the MainClass from your Dice class.

I hope that's even kind of helpful!
capnKate
Freshman
Freshman
 
Posts: 8
Joined: Mon Jun 21, 2010 6:55 pm

Re: Getting View resources from class

Postby vengeance_mj » Wed Jun 23, 2010 8:00 am

You need to inflate the view main.xml use Layout Inflater so that findViewById won't return null. Hopefully that helps
vengeance_mj
Senior Developer
Senior Developer
 
Posts: 174
Joined: Thu Oct 29, 2009 2:32 am

Top

Return to Code Snippets for Android

Who is online

Users browsing this forum: No registered users and 3 guests