Reputation: 5413
I have an APP, bundle ID is com.MYAPP, and then I create a new package named com.reference and inside that has ViewCache file. It first generated error on findViewById(R.id.text) and findViewById(R.id.image) so, I had to import com.MYAPP.R to rid of the errors. But under the Layout folder I have many .xml layout files that could use the id of =R.id.text and R.id.image. I thought I need to specifiy a specific xml to pointed to so ViewCache know exactly which xml it used. I thought I need to import com.MYAPP.R.row_item.xml.
I also has mainapp.xml that use id.text and id.view.image under the layout folder. but it would NOT let me specify import com.MYAPP.R.row_item.xml.
So What should I specify on the import? I think import com.MYAPP.R is Not enough.
package com.reference;
import com.MYAPP.R;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ViewCache {
private View baseView;
private TextView textView;
private ImageView imageView;
public ViewCache(View baseView) {
this.baseView = baseView;
}
public TextView getTextView() {
if (textView == null) {
textView = (TextView) baseView.findViewById(R.id.text);
}
return textView;
}
public ImageView getImageView() {
if (imageView == null) {
imageView = (ImageView) baseView.findViewById(R.id.image);
}
return imageView;
}
}
Upvotes: 0
Views: 1477
Reputation: 49612
To clarify some naming: What you call bundle id (com.MYAPP) is your application package (which is defined in the manifest file).
The R.java file contains all ids generated from your resources. It is located in <application-package>.R
(so in your case com.MYAPP.R
). If you define the same id in multiple layout file it will result in a single id within the R file.
findViewById(id)
looks in a view for a child view with the specified id. It does NOT look for a view with this id in all your layout files.
If you do the following for example:
public class MyActivity extends Activity {
public void onCreate(Bundle b) {
super.onCreate(b);
this.setContentView(R.layout.myView); // you set the view here
TextView tv = (TextView) findViewById(R.id.text); // this looks in the layout myView for an item with id text
}
}
In your example findViewById(..)
will look for a childview with id text
within baseView
. Only baseView
will be searched for an element with id text
, not any of the other layouts. So the result of findViewById(..)
depends on what you assign to baseView.
Upvotes: 1