Reputation: 2204
I made a custom view which I called Game.java
public class Game extends View {
public Game(Context context, AttributeSet attrs) {
//here goes class
public void shot(){
}
//method I want to use sometime
}
here's part of my layout file for Activity game.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GameActivity" >
<com.vladdrummer.textmaster.Game
android:id="@+id/game"
android:layout_width="wrap_content"
android:windowSoftInputMode="adjustResize"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<View
android:id="@+id/spareview"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
etc.. So, in Activity I simply do
setContentView(R.layout.game);
and I got my custom View class called Game.java as the part of the screen
But how do I address it? if I do :
Game game;
game =(Game) findViewById(R.id.game);
game.shot();
it crashes.
of course , I can do :
Game game=new Game(this)
setContentView(game);
and have access to game so it won't crash, but I need other elements on screen as well
please tell me how to do it right
Upvotes: 0
Views: 53
Reputation: 133560
You can have a RelativeLayout
or LinearLayout
in your xml and place it anywhere you want. You can have other views in xml also. This is one way
setContentView(R.layout.yourlayout); // infalte layout
RelativeLayout rl =(RelativeLayout) findViewById(R.id.relativeLayout);// initialize
Game game=new Game(this);
rl.addView(game); // ad view to container
But you have the custom view in your layout. You are missing constructors in GameView
. Your method also should also work
Read Chapter 4 Creating user Interface by Retro Meier Professional Android Devleopment
Upvotes: 1