I am a web dev and very new to android dev and OOP so I might be making a mistake in how I approach this problem. This seems like a very simple problem.
So I made a custom view called GridView
that contains a setter function where I can set a grid
to that class which basically looks like this.
public class GridView extends View {
public Grid grid;
public GridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setGrid(Grid grid) {
this.grid = grid;
invalidate();
}
}
Then it renders that grid
on the android canvas with the onDraw
function.
I create an instance of this GridView
in my android activity so I can use it here. This is basically how that looks.
public class MyActivity extends AppCompatActivity {
public GridView gridView;
public Grid grid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
grid = new Grid(20, 20);
gridView = new GridView(this, null);
gridView.setGrid(grid);
setContentView(R.layout.my_activity);
}
}
I have listed that GridView
in the my_activity.xml file like this:
<view
android:id="@+id/gridView"
class="com.dev.myapp.GridView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:background="@android:color/transparent"
android:fadingEdge="vertical"
android:gravity="top"
android:padding="5dp"
android:scrollbars="vertical" />
The problem is that the grid
variable is null inside the GridView
class when I create an instance of GridView
in MyActivity.java
and pass in the grid
in the setGrid
setter function.
However, it works perfectly fine when I create the grid
instance directly in the GridView
constructor like this:
public class GridView extends View {
public Grid grid;
public GridView(Context context, AttributeSet attrs) {
super(context, attrs);
grid = new Grid(20, 20);
}
}
I think the problem might be because I am directly rendering the GridView
class on the my_activity.xml
file so it is rendering whatever is in that particular file instantly and it is not rendering the instance of that GridView
that I have created in the MyActivity.java
.
How am I supposed to render the instance of the GridView
that I create in MyActivity.java
on the my_activity.xml
?
<com.dev.myapp.GridView
android:id="@+id/gridView"
... />
val gv = findViewById<GridView>(R.id.gridView)
gv.setGrid(grid)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.