litterbugkid
litterbugkid

Reputation: 3666

How to get layout components not on an Acitivty's own layout

I'm trying to manipulate components not on an Activity's own layout view. How would I reference them?

I have the resource ID but when I try to reference them using:

DatePicker date = ((DatePicker) findViewById(resID));

.. I get a NullPointerException.

Upvotes: 1

Views: 3039

Answers (2)

Huang
Huang

Reputation: 4842

If you want to get views in different layout xml file, the best practice is to use a LayoutInflater to inflate(load) these files. You can do something like this:

LayoutInflater inflater;
View firstView;
View secondView;
Button aboutFirst;
Button aboutSecond;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);//initialize the layout inflater
    firstView = inflater.inflate(R.layout.firstview, null); // inflate firstview.xml layout file
    secondView = inflater.inflate(R.layout.secondview, null);//inflate secondview.xml layout file
    aboutFirst = (Button) firstView.findViewById(R.id.button1);//get button  in firstview.xml
        aboutSecond = (Button) secondView.findViewById(R.id.button1);//get button in secondview.xml
}

Upvotes: 3

Jwc24678
Jwc24678

Reputation: 161

The only solution that I found to this was to change the current content view to the one that holds the View you're trying to find:

setContentView(R.layout.second_layout);
DatePicker date = ((DatePicker)findViewById(resID));
setContentView(R.layout.main);

then changing back to the original layout. I'm still looking for a better solution, but this is what I've got currently.

Upvotes: 0

Related Questions