When I call findViewById()
to get a button (in the form of an ImageView
), it returns null
. I have looked over these suggestions and I can tell that
findViewById()
is called aftersetContentView()
.- There is only one layout:
activity_main.xml
. - I am not using
ExpandableListView
. - Both
findViewById()
andtopbar.findViewById()
returnnull
.
What else might I have overlooked?
activity_main.xml
<LinearLayout>
<GridView
android:id="@+id/topbar_grid">
</GridView>
</LinearLayout>
Mainactivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeTopBar();
initializeMenu();
}
private void initializeTopBar() {
GridView topbar = (GridView) findViewById(R.id.topbar_grid);
TopBarAdapter topBarAdapter = new TopBarAdapter(this);
topbar.setAdapter(topBarAdapter);
ImageView playButton = (ImageView) findViewById(topBarAdapter.playButtonId);
// Debugging shows playButton is null here
// Removing the below statement results in the app
// being displayed just fine
playButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
onPlayButtonClick();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
TopBarAdapter.java
public class TopBarAdapter extends BaseAdapter {
private Context context;
private View[] views = new View[2];
public int playButtonId = 2000;
public int trackLabelId = 2001;
public TopBarAdapter(Context c){
context = c;
createTrackLabel();
createPlayButton();
}
private void createPlayButton(){
ImageView playButton = new ImageView(context);
playButton.setImageResource(R.drawable.play_icon);
playButton.setScaleType(ScaleType.CENTER_CROP);
playButton.setLayoutParams(new GridView.LayoutParams(50, 50));
playButton.setId(playButtonId);
views[1] = playButton;
}
@Override
public int getCount() {
return views.length;
}
@Override
public Object getItem(int position) {
return views[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return views[position];
}
}