Reputation: 38
I have a problem with findViewById using Java in Android Studio. I'm triying to obtain a Constraint Layout to use .addview in it but it returns null.
This is the layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/gameLayout"
tools:context=".GameActivity">
This is the line with problems:
ConstraintLayout mainLayout = (ConstraintLayout) findViewById(R.id.gameLayout);
And it returns null, what am I doing bad?
Thanks
Edit: Now I'm getting stucked afther this loops, what can be?
protected void generateGameZone(int m, int n){
LinearLayout[] main_layouts = new LinearLayout[m];
for(int i=0;i<main_layouts.length;i++){
main_layouts[i] = new LinearLayout(this);
main_layouts[i].setOrientation(LinearLayout.HORIZONTAL);
main_layouts[i].setLayoutParams(new LinearLayout.LayoutParams(30,30));
mainLayout.addView(main_layouts[i]);
}
LinearLayout[][] secondary_layouts = new LinearLayout[m][n];
for(int i=0;i<secondary_layouts.length;i++){
for(int j=0;j<secondary_layouts[i].length;j++){
secondary_layouts[i][j] = new LinearLayout(this);
secondary_layouts[i][j].setOrientation(LinearLayout.HORIZONTAL);
secondary_layouts[i][j].setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
TextView txtBox = new TextView(this);
txtBox.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
txtBox.setId(i*10 + j);
secondary_layouts[i][j].addView(txtBox);
main_layouts[i].addView(secondary_layouts[i][j]);
}
}
}
I obtain a black screen
Edit2: Black screen solved, now the layout I create with loops its not being showed
Upvotes: 0
Views: 645
Reputation: 5990
From your question it seems like you are trying to add the ConstraintLayout
programmatically to your activity. However findViewById(int)
called from an Activity
tries to find the already existing view in the hierarchy and returns null
if it isn't found.
I think what you are looking for is either to inflate the layout using a LayoutInflater
and then add it using addView
as you suggested, or if this layout represents the root of your activity, use setContentView(int)
to let the activity handle the inflation.
Upvotes: 1