I have done I game in which I want to call on a method I have in a view from another view. I figured I would somehow have to send the "first view" into the "second view" through the my MainActivity in order for the second view to be able to call on the first view methods. However, I couldn't come up with any way of sending in the first view to the second view through my MainAcitivity, so I decided to change tactics. I now tried to have a function in my MainActivity to handle the interection between the views, but once again I was not able to call on the method from the second View.
Therefore my question is how do you send a view into another view through an Activity, or If that's not possible how do you call on an activity method through a view?
Here is the code (I added some comments to better show the problem I'm having):
public class MainActivity extends AppCompatActivity {
private FishView gameView;
private SmallBall smallBall ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout screen = findViewById(R.id.gameScreen);
gameView = new FishView(this);
smallBall = new SmallBall(this);
screen.addView(gameView); // first view
screen.addView(smallBall); //second view
}
//this is the method I want to reach through the View
public void handleAvoidedBall(){
gameView.avoidedBall();
}
}
public class SmallBall extends View {
private final Bitmap sodaCan;
private final static long smallBallPeriod = 60;
private final Handler handler = new Handler();
public SmallBall(Context context) {
super(context);
Paint smallBall = new Paint();
smallBall.setColor(Color.GRAY);
smallBall.setAntiAlias(false);
resetBall();
sodaCan = BitmapFactory.decodeResource(getResources(),R.drawable.sodacan);
Timer movementTimer = new Timer();
movementTimer.scheduleAtFixedRate(smallBallTask, 0, smallBallPeriod);
}
private final TimerTask smallBallTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
invalidate();
if (isBallLanded()){
//Here I want to call on a handleAvoidedBall() in MainActivity
//OR simply have gameView here if possible
// gameView.avoidedBall();
//OR
//SomeMainAcitvityObject.handleAvoidedBall();
}
}
});
}
};
#Override
protected void onDraw(Canvas canvas) {
..... //Do stuff}
}
So as I hopefully have explained somewhat decent now, I'm wondering how to either send gameView into the SmallBall view OR how to call on handleAvoidedBall() in MainActivity from the SmallBall view?
Thank you for your time and hope you have a wonderful day!
Your best option would be to define a listener that you would set on the SmallBallView.
Define the listener:
public interface BallListener {
void onAvoided(SmallBall ball);
}
And then inside your SmallBall class, you would have this method:
public void setListener(BallListener listener){
this.listener = listener;
}
And then call this in your activity, after you've instantiated the SmallBall class:
smallBall.setListener(new SmallBallListener(){
#Override
public void onAvoided(SmallBall ball){
// Do stuff here
}
})
As #LukeWaggoner mentioned, you should consider using listeners instead of making view static in your activity.
You told us, that you'd like to add more than one SmallBall views, so I figure that you don't want to write a listener's code for each of them.
It is easily doable with MainActivity implementing SmallBallListener.
Listener:
public interface SmallBallListener {
void onAvoidedBall();
}
SmallBall class:
public void setListener(SmallBallListener listener){
this.listener = listener;
}
MainActivity:
public class MainActivity extends AppCompatActivity implements SmallBallListener {
private FishView gameView;
private SmallBall smallBall ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout screen = findViewById(R.id.gameScreen);
gameView = new FishView(this);
screen.addView(gameView); // first view
// Add 10 small ball views
for(int i = 0; i < 10; i++) {
SmallBall ball = new SmallBall(this);
ball.setListener(this); // MainActivity is a listener here, so each ball has the same listener code
screen.addView(ball);
}
}
//this is the method I want to reach through the View
public void handleAvoidedBall() {
gameView.avoidedBall();
}
#Override
public void onAvoidedBall() { // this is the SmallBallListener method
this.handleAvoidedBall();
}
}
So whichever SmallBall view call listener.onAvoidedBall(), it will fire onAvoidedBall() method in MainActivity class.
Turns out all I had to do was to set:
private FishView gameView;
to:
public static FishView gameView;
And then simply use "MainActivity.gameView" in the SmallBall view. This gave me no additional warings either, so that was good also.
Related
I have a class SomeView that extends View and that is displayed in a class Controls that extends linear layout.
The linear layout is instantiated onCreate of an activity.
I would like to call a method in the activity every time I click on this view SomeView.
I have tried to set an onClickListener in the activity like this
public class MainActivity extends AppCompatActivity implements
SomeView.OnClickListener {
private Controls menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
menu = new Controls(this);
menu.getSomeView().setOnClickListener(this);
setContentView(menu);
}
#Override
public void onClick(View view) {
System.out.println("Hello");
}
}
The controls class looks like this
public class Controls extends LinearLayout {
private SomeView aview;
public Controls(Context context) {
super(context);
this.setOrientation(LinearLayout.HORIZONTAL);
aview = new SomeView(context);
this.addView(aview, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
public SomeView getSomeView() {
return aview;
}
}
and the SomeView class looks like this (it just draws an oval)
public class SomeView extends View {
public SomeView(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
RectF aRect = new RectF();
aRect.left = getPaddingLeft();
aRect.top = getPaddingTop();
aRect.right = getWidth() - getPaddingRight();
aRect.bottom = getHeight() - getPaddingBottom();
Paint aPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
aPaint.setColor(Color.GREEN);
canvas.drawOval(aRect, aPaint);
}
}
But I am missing something because clicks are not calling the onClick method.
What else do I need to set up?
it seems like you did only mistake in your MainActivity class, where you forgot to call the super method. Try doing this, hope it will work, since it works from here in my mobile.
Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
menu = new Controls(this);
menu.getSomeView().setOnClickListener(this);
setContentView(menu);
}
And in your callback method, instead using System.out.println(), use Log.d() as below:
#Override
public void onClick(View view) {
Log.d(TAG, "Hello");
}
and it is working from here, look at the image below as well.
I have searched but could not find answer of my question.
This is what I have:
private class BoxView extends View {
private String caption;
private OnClickListener bvClickListener = null
public BoxView(Context context) {
super(context);
this.bvClickListener = new this.OnClickListener(){
public void onClick (View v){
/*v.setCaption("X"); view don't have this method */
}}
}
public void setCaption(String s){
this.caption=s;
invalidate();
}
}
This is what I want to have:
private class BoxView extends View {
private String caption;
private OnClickListener bvClickListener = null
public BoxView(Context context) {
super(context);
this.bvClickListener = new this.OnClickListener(){
public void onClick (BoxView bv){
bv.setCaption("X");
}}
}
public void setCaption(String s){
this.caption=s;
invalidate();
}
}
I may need custom methods for my custom views. And I want to be able to pass my custom view instead of view version of it when onclick is triggered so I can access to it directly.
Updated
And I want to have access to real object not a converted one. So I want to avoid this:
public void onClick (View v){
((BoxView)v).setCaption("X");
}
Call setCaption method as in onClick :
public void onClick (View v){
((BoxView)v).setCaption("X");
}
Try this
class Main extents Activity
{
BoxView boxView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// if view is used using layout then
boxView = (BoxView)findViewByID(id);
//else if directly used
boxView = new BoxView(this);
box.setOnClickListener(new onClickListener()
{
#Override
public void onClick(View view) {
boxView.setCaption("X");
boxView.invalidate();
}
});
}
}
Calling onBackPressed method of Activity class on a View Class? is it possible? and so how can I? thanks for help
UPDATE: I just created the GameView of my Game which is extends to View Class. I create a variable that increments whenever I finish every level so it will limit a levels per game. And so I want to implement a onBackPressed method which I can set the incrementing variable back to zero whenever the player press the back key.
FULL CODE: MAIN ACTIVITY
public class MainActivity extends Activity {
private GameView mGameView;
#Override
public void onBackPressed() {
if (mGameView.interceptBackPressed()) {
return;
}
// TODO Auto-generated method stub
super.onBackPressed();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mGameView = (GameView) findViewById(GameView.countmaze);
Afterwards it goes to Menu Class
public class menu extends Activity implements OnClickListener {
static int nextmaze;
int countmaze = 0;
GameView gameView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnplay = (Button) findViewById(R.id.btnPlay);
btnplay.setOnClickListener(this);
}
#Override
public void onBackPressed() {
//I have here an AlertDialog builder
}
#Override
public void onClick(View v) {
case R.id.btnPlay:
Toast.makeText(getApplicationContext(), "LEVEL 1",
Toast.LENGTH_SHORT).show();
startnextmaze();
}
}
void startnextmaze() {
Random rand = new Random();
Intent game = new Intent(menu.this, Game.class);
nextmaze = rand.nextInt(5) + 1;
Maze maze = MazeCreator.getMaze(nextmaze);
game.putExtra("maze", maze);
startActivity(game);
}
Then on my GameView Class
public class GameView extends View {
static int countmaze;
//Big codes here......
public boolean interceptBackPressed() {
// TODO Auto-generated method stub
countmaze = 0;
return true;
}
}
Create a callback on the Activity onBackPressed that the View class will implement
Example
public void interface onBackPressedHandler {
public void onBackPressed();
}
Activity Class
public onBackPressedHandler mHandler;
#Override
public void onCreate(....) {
GameView game... //Inflate or create.
game.setActivity(this);
}
public void setListener(onBackPressedHandler handler) {
mHandler = handler;
}
#Override
public voind onBackPressed() {
if(mHandler != null) {
mHandler.onBackPressed();
}
super.onBackPressed();
View Class
public GameView extends View implements onBackPressedHandler {
public void setActivity(Activity activity) {
activity.setListener(this);
}
public void onBackPressed() {
//your code here.
}
}
This example shows when you press the back Button it will call the onBackPress on the View.
Hope it Helps.
Update your code with the following changes:
Activity
public class MyActivity extends Activity {
private GameView mGameView;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main);
//View reference to object defined in XML
mGameView = (GameView) findViewById(R.id.gameview);//id must be specified in XML
//I assumed that GameView is a part of your XML layout
//View created programmatically.
mGameView = new GameView(this);
//Use one of the above initialisation techniques of mGameView.
}
#Override
public void onBackPressed() {
//here we are calling method on mGameView which cannot be null
//that's why we initialised it in onCreate() method
if (mGameView.interceptBackPressed()) {
return;
}
super.onBackPressed();//finish your Activity
}
}
GameView
public class GameView extends View {
public boolean interceptBackPressed() {
//TODO handle your game logic here and return true if you don't
//want your game to be shutdown, otherwise return false
return true;
}
}
I want to create by code an array of objects that are subclasses of Button.
public class MyButton extends Button {
private Context ctx;
private int status;
public MyButton(Context context) {
super(context);
ctx = context;
status = 0;
}
private click() {
status = 1;
// OTHER CODE THAT NEEDS TO STAY HERE
}
}
In the main activity I do this:
public class myActivity extends Activity {
private MyButton[] myButtons = new MyButton[100];
#Override
public onCreate(Bundle si) {
super.onCreate(si);
createButtons();
}
private void createButtons() {
for (int w=0; w<100; w++) {
myButtons[w] = new MyButton(myActivity.this);
myButtons[w].setOnClickListener(new View.onClickListener() {
public void onClick(View v) {
// ... (A)
}
});
}
}
}
Now I want the click() method inside MyButton to be run each time the button is clicked.
Seems obvious but it is not at my eyes.
If I make the click() method public and run it directly from (A), I get an error because myButtons[w].click() is not static and cannot be run from there.
In the meantime, I an not able to understand where to put the code in the MyButton class to intercept a click and run click() from there. Should I override onClick? Or should I override onClickListener? Or what else should I do?
How can I run click() whenever one of myButtons[] object is clicked?
Thanks for the help.
You can cast View v you got in listener to MyButton and call click on it:
private void createButtons() {
View.OnClickListener listener = new View.onClickListener() {
public void onClick(View v) {
((MyButton) v).click();
}
};
for (int w=0; w<100; w++) {
myButtons[w] = new MyButton(myActivity.this);
myButtons[w].setOnClickListener(listener);
}
}
you can add:
View.onClickListener onclick = new View.onClickListener() {
public void onClick(View v) {
((MyButton)v).click();
//since v should be instance of MyButton
}
};
to your Activity
then use:
myButtons[w].setOnClickListener(onclick);
//one instance of onclick is enough, there is no need to create it for every button
in createButtons()
but ... why, oh why array of buttons we have ListView in android ...
My Activity has multiple lists so I have defined MyClickListener as below:
My question is how I should instantiate this class:
MyClickListener mMyClickListener = new MyClickListener();
Or maybe it is better to instantiate inside the onCreate(Bundle) and just define above. Whats considered the better way? I don't want too much in onCreate() its already full of stuff. Any thoughts on the declaration and instatiation? Whats the best way?
private class MyClickListener implements OnClickListener
{
#Override
public void onClick(View view) {
}
}
I use same kind of class mechanism as you mentioned in the question.
this is the way i use,
public class myActivity extends Activity
{
private MyListener listener = null;
private Button cmdButton = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cmdButton = (Button) findViewById(R.id.cmdButton);
cmdButton.setOnClickListener(getListener());
}
// method to fetch the listener object
private MyListener getListener()
{
if (listener == null)
{
listener = new MyListener();
}
return listener;
}
private class MyListener implements Button.OnClickListener
{
public void onClick(View v)
{
}
}
}
Why are you instantiating a listener like that in the first place? Just create a new one when you assign it to your listView.
listView.setOnClickListener( new MyListener());