Android: Passing data from surfaceView to its parent activity - java

I am having trouble sending info from a surfaceView class to its parent class
the overlay activity sets its view as a drawing panel:
public class Overlay extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Overlay);
drawingPanel dPanel = new drawingPanel(this);
setContentView(dPanel);
}
}
then in the drawing panel:
public class drawingPanel extends SurfaceView implements SurfaceHolder.Callback {
Context context = context;
public Player(Context context, int num) throws ClassNotFoundException, IOException {
super(context);
this.context = context;
SurfaceHolder holder = getHolder();
holder.addCallback(this);
}
public boolean onTouchEvent(MotionEvent e){
if(e.getAction()==MotionEvent.ACTION_DOWN){
//send info to Overlay that drawingPanel was touched
}
}
}
When surfaceView is touched, I want to send that info to Overlay. I can't simply use onTouchEvent in the Overlay activity because I need to draw stuff with drawingPanel. My main goal is to hide/show the action bar when the screen is touched while using a surfaceView. if there is another way to achieve that, please state so below.

Try adding this line to onCreate method of your Overlay class
dPanel.setActivity(this);
And implementing setActivity() in the drawingPanel class like this:
public void setActivity(Activity overlayActivity) {
mActivity = overlayActivity;
}
This way, you can use mActivity to reference your Activity and call public methods to "hide/show the action bar", like:
mActivity.getActionBar().hide();
and,
mActivity.getActionBar().show();

Related

Android - How to call method in custom View from Main Activity?

I have created a custom View that will display a circle (the idea is that the user will be able to interact with this "ball" in various ways)
From my main activity class, I want to adjust some of the "ball's" properties, in this case change its color.
My problem is that nothing happens (no errors either, the app runs but doesn't do what I want) when I try to call the various methods from my MainActivity class, but if I do it from CircleView class, it works (for example changing the color upon touch)
Here is my custom View class (CircleView.java):
public class CircleView extends View {
private int circleColor = Color.GREEN;
private Paint paint;
public CircleView(Context context) {
super(context);
init(context, null);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_SCROLL:
this.circleColor = setRandomColor();
invalidate();
break;
case MotionEvent.ACTION_DOWN:
this.circleColor = setRandomColor();
invalidate();
break;
}
return super.onTouchEvent(event);
}
public CircleView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
paint = new Paint();
paint.setAntiAlias(true);
}
public void setCircleColor(int circleColor) {
this.circleColor = circleColor;
invalidate();
}
public int setRandomColor() {
Random random = new Random();
int randomColor = Color.argb(255, random.nextInt(), random.nextInt(), random.nextInt());
return randomColor;
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//...
//someXvalue, someYvalue, someRadius are being set here
//...
paint.setColor(circleColor);
canvas.drawCircle(someXvalue, someYvalue, someRadius, paint);
}
}
And here is my MainActivity.java class:
public class MainActivity extends Activity implements
GestureDetector.OnGestureListener {
private GestureDetectorCompat mDetector;
CircleView circle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDetector = new GestureDetectorCompat(this, this);
circle = new CircleView(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
this.mDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
#Override
public boolean onDown(MotionEvent event) {
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent event) {
circle.setCircleColor(circle.setRandomColor(0));
circle.invalidate();
return true;
}
}
I am new to Android development, and Java as well. I realize it could be something with the Context, which is something I have not fully understood yet. Could also be something with the TouchEvents. I am sure that someone out there can see my mistake. Any help is appreciated.
your circle view is not a part of activity's layout , it's just a object in memory which has no link to your activity screen so solutions
1.) Either set circle as Activity's view
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDetector = new GestureDetectorCompat(this, this);
circle = new CircleView(this);
setContentView(circle);
}
2.) you can create your <yourpackagename.CircleView ...attributes .../> tag in your activity_main.xml and then use findViewById to initialize it in your activity.
1)If all you want to do with gestures is on tap, just implement an onClickListener on your View instead.
2)You aren't actually using the GestureDetector anywhere. The way it works is you set an onTouchListener for the view you want to get gestures on, and send the events to the gesture detector. You aren't ever sending data for any view to the detector, so it will never do anything.
3)Not a bug just an oddness- why circle.setColor(circle.setRandomColor())? I would expect a function named setXXX to actually set XXX, rather than having to do it yourself later. Not following that convention will work, but make debugging and maintenance hard.
Edit: Also what #Pavneet_Singh said- your circle isn't in your layout anywhere, so it won't be on screen.

send data from unity to java android

I created an unity project and I'm trying to send data from c# to unity. on my c# code I implemented this code :
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("shareText","test","test");
It works on android on my activity :
public class UnityActivity extends AppCompatActivity {
public void shareText(String AppId,String PublisherID) {
Log.e("test","test");
Log.e("test",AppId);
Log.e("test",PublisherID);
}
}
but in another case I created a custom view containing unityPlayer.
So now I have UnityActivity containing UnityView (which is a java class) and the last one contain my custom view (extend linearLayout) with unityPlayer and with the same code it didn't work :
public class CstUnityView extends LinearLayout {
private UnityPlayer mUnityPlayer;
public void shareText(String AppId,String PublisherID) {
Log.e("test","test");
Log.e("test",AppId);
Log.e("test",PublisherID);
}
}
Anyone have an idea why it didn't work ?!
So your problem is that the shareText() in your custom linearlayout cannot be called by unity unless it is declared in activity. It needs to be declared in your activity in order for your unity Call to ignite the function.
You can check the console log first to make sure it has been called.
After, you can use those that you have received from your activity to your custom layout view.
in your activity
protected UnityPlayer mUnityPlayer;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//this creates unityplayer with context to your activity
mUnityPlayer = new UnityPlayer(this);
//this requests focus so that the currentactivity is set to your activity
//that is why shareText() can be called from your Unity
mUnityPlayer.requestFocus();
//call layout here
yourLinearlayout customlayout = new yourLinearLayout();
//do what you want to do with this customlayout
//....
}
public void shareText(String AppId,String PublisherID) {
Log.e("test","test");
Log.e("test",AppId);
Log.e("test",PublisherID);
}

FindViewById in a non activity class

How can I use findViewById() in a non activity class. Below is my code snippet. I get the error message: "can't resolve method findViewById" if used directly. And if i try to use the class constructor (Where the imageView is available) i get this error "cannot resolve symbol context"
public class MyBroadcastReceiver extends FirstBroadcastReceiver {
Activity activity;
public MyBroadcastReceiver(Context context, Activity activity){
this.context=context; // error here(cannot resolve symbol context)
this.activity=activity;
}
#Override
protected void (Context context) {
// content
}
#Override
public void onButton(Context context, boolean isClick) {
if(isClick) {
ImageView blueImage = (ImageView)activity.findViewById(R.id.imageView);
blueImage.setColorFilter(0xff000000);
}
}
.......
....
// and so on
And below is my MainActivity with MybroadcastReceiver class instance.Is it correct?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// and so on
}
}
MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver(MainActivity.this,this);
#Override
public void onActivityResult() {
// some code
}
#Override
public void onInitialized(MyManager manager){
// some code
}
A BroacastReceiver runs entirely in the background, listening for Intents sent either by the OS or other apps. It is not responsible for any UI interactions, and cannot access any views. Therefore, findViewById cannot be used within a BroadcastReceiver.
See also - What is BroadcastReceiver and when we use it?
You have to pass View to the non activity class, before using findViewByid
and
try using
view.findViewByid(R.id.view_id);
Because context is null in Broadcast class. use Broadcast class constructor to pass parent_activity(Where the imageView is available) context in Broadcast to access the context:
public class Broadcast extends BroadCastReceiver {
Activity activity;
public Broadcast(Context context,Activity activity){
this.context=context;
this.activity=activity;
}
.......
....... //so on
and in parent_activity create Broadcast class instance by passing parent_activity context as:
Broadcast broadcast = new Broadcast(parent_activity.this,this);
Use activity instance as:
#Override
public void onButton(Context context, boolean isClick) {
if(isClick) {
ImageView blueImage = (ImageView) activity.findViewById(R.id.imageView); //<--- here
}
}
.........
......... //so on

SurfaceView getHolder returns null

I read other questions on this, but I feel like my architecture is a bit different, so I'm posting.
I have a game with one MainActivity and multiple views. Basically, there is one LinearLayout that fills MainActivity, and different views are set on the layout depending on the state. For example, menuState (menuView), gameState (gameView), gameOverState (gameOverView).
In my BattleView (which extends SurfaceView), I tried to implement a game loop. However, my BattleView cannot implement a Callback due to the fact getHolder() returns null.
How would I go on about fixing this?
public class MainActivity extends AppCompatActivity {
GameScreen gs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.init();
}
private void init(){
this.gs = new GameScreen(this);
this.hideSystemUI(this.gs);
setContentView(this.gs);
}
Then my GameScreen class contains BattleView class, which is called when appropriate.
public GameScreen(Context context){
super(context);
this.init();
}
private void init(){
this.ms = new MapScreen(this.getContext(), this);
((MainActivity)this.getContext()).hideSystemUI(this.ms);
this.addView(this.ms);
}
private void newMapScreen(){
this.ms = new MapScreen(this.getContext(), this);
}
public void addBattleScreen(BattleScreen bs){
//this.bs = new BattleScreen(this.getContext(), ms);
this.removeView(this.ms);
this.bs = bs;
((MainActivity)this.getContext()).hideSystemUI(this.bs);
this.addView(this.bs);
}
Well.. BattleScreen contains BattleView class and is initialized there. Then, BattleView class
public BattleView(Context context, int monsterNumber, Hero hero){
super(context);
this.gameLoopInit();
this.setBackgroundImage();
}//end
private void gameLoopInit(){
holder = getHolder(); <------------- ERROR (null)
System.out.println(holder);
holder.addCallback(this);
}

Java object notify parent class

I am developing an augmented-reality app in Android. I have one class which called AugmentedView, extends view and it is responsible to draw the markers. In the onDraw method when it detects collisions i want to notify the parent class which is the main class and contains the main gui to enable one button in the screen. I call the AugmentedView class in the onCreate of Main class with the following code:
AugmentedView augmentedView = new AugmentedView(this);
augmentedView.setOnTouchListener(this);
augmentedView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
liveLayout.addView(augmentedView);
How can i notify the main class for the changes and pass the List of markers to it?
If I'm understanding your problem correctly , you want to notify the Activity/Fragment that contains your AugmentedView.
A simple way to do that is by using java callbacks.
// in Activity
//onCreate() ..
AugmentedView augmentedView = new AugmentedView(this);
augmentedView.setOnTouchListener(this);
augmentedView.setCollisionlistener(new Collisionlistener());
augmentedView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
liveLayout.addView(augmentedView);
}
..
public class Collisionlistener {
public void onCollosion (){
// write code to handle collosion
}
}
// in your AugmentedView
private Collisionlistener mListener;
public void setCollisionlistener(Collisionlistener listener){
mListener = listener;
}
public void onDraw(Canvas canvas){
// your code
if (collosionDetected && mListener != null) {
mListener.onCollosion();
}
}

Categories