How can I construct this scenario?
I want to build a game where the game board is a canvas controlled by a custom View but within a ScrollView. The game board is potentially much bigger than the screen and I want to scale, scroll around the game. However, I want all the advantages of the UI outside the game board to include Buttons, TextViews, ImageViews, etc.
Here’s the outline code of what I imagine should work. Am I wrong in thinking I can use both
my own onDraw and expect buttons and other widgets to be managed by Android? Must I implement
all my own UI ? Just trying to deal with a Button (see below) fails me Here’s the XML where I want my custom view surrounded by other UI elements.
I’ve looked at a lot of other examples and tutorials but have yet to see a custom view placed with an activity with UI elements around it.
My main activity
// Activity
public class gameStartActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
}
}
My custom view
// gameView.java
public class gameView extends View {
public gameView(Context context) {
super(context);
setFocusable(true); //necessary for getting the touch events
InitBoardView();
}
private void InitBoardView(){
Button myButton = (Button)findViewById(R.id.editname);
-----> fails at this point as myButton is null
myButton.setOnClickListener(doSomething);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(face, getPaddingLeft(), getPaddingTop(),paint);
}
@Override
protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
setMeasuredDimension(xSize, ySize);
}
game.xml
<ScrollView
android:layout_width="240dp"
android:layout_height="600dp"
<com.android.example.game.gameView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</ScrollView>
<TextView
android:id="@+id/sometext
android:layout_width="120dp"
android:layout_height= "wrap_content"
android:layout_weight="1"
android:visibility="gone"/>
<Button
android:id="@+id/editname"
android:text="DoIt"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
</Button>
findViewById() would work in a custom view only if:
– You extend from ViewGroup (or another subclass of ViewGroup)
– The Button is a child of your custom view
A better way of doing this would be to find the button in the Activity and set its listener there. You could also have a setButton(Button view) method in your custom view and have the activity do the following: