How to transfer data between an Activity and a View class? - java

I want to transfer 2 float values and 1 boolean value from my MainActivity class to MyCanvas class (which is a class extends View)? Is this possible?
I know this a newbie question, but everything that I found told to use Intent and Bundle, or to use only Bundle.setArguments(), but apparently, none of them work for a View class.
Thank you.
EDIT 1
This is my MainActivity
public class MainActivity extends AppCompatActivity {
private MyCanvas myCanvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myCanvas = (MyCanvas) findViewById(R.id.canvas);
}
public void btnCalcularOnClick(View v) {
TextView xResultado = (TextView) findViewById(R.id.xResultado);
TextView yResultado = (TextView) findViewById(R.id.yResultado);
EditText txtX = (EditText) findViewById(R.id.txtX);
EditText txtY = (EditText) findViewById(R.id.txtY);
//Comeco da Matematica
float x = Float.parseFloat(txtX.getText().toString());
float y = Float.parseFloat(txtY.getText().toString());
float xResult = 5 * x;
float yResult = 35 * y;
boolean buttonState = true;
}
}
MyCanvas class is like that
public class MyCanvas extends View {
Paint myPaint;
public MyCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
myPaint = new Paint();
}
#Override
public void onDraw(Canvas myCanvas) {
super.onDraw(myCanvas);
myPaint.setColor(Color.BLACK);
myPaint.setStrokeWidth(3);
float cx, cy;
boolean buttonState2;
}
}
In this case, I want to transfer:
xResult (MainActivity) -> cx (MyCanvas)
yResult (MainActivity) -> cy (MyCanvas)
buttonState (Main Activity) -> buttonState2 (myCanvas)

You can use setters to set the desired values in your MyCanvas class.
Create methods in your MyCanvas class like this.
public class MyCanvas extends View {
private float cx, cy;
private boolean buttonState2;
...
public void setResults(float xResult, float yResult) {
cx = xResult;
cy = yResult;
}
public void setButtonState(boolean state) {
buttonState2 = state;
}
}
Then in your activity class
public class MainActivity extends AppCompatActivity {
private MyCanvas myCanvas;
...
public void btnCalcularOnClick(View v){
TextView xResultado = (TextView)findViewById(R.id.xResultado);
TextView yResultado = (TextView)findViewById(R.id.yResultado);
EditText txtX= (EditText)findViewById(R.id.txtX);
EditText txtY= (EditText)findViewById(R.id.txtY);
//Comeco da Matematica
float x = Float.parseFloat(txtX.getText().toString());
float y = Float.parseFloat(txtY.getText().toString());
float xResult = 5 * x;
float yResult = 35 * y;
boolean buttonState = true
myCanvas.setResults(xResult, yResult);
myCanvas.setButtonState(buttonState);
}
}

Create static variable and use it in your MyCanvas class.
In MainActvity:-
public static float var1 = 1.0f;
public static float var2 = 2.0f;
public static boolean var3 = true;
And in your MyCanvas class:-
private float var1InCanvas = MainActivity.var1;
private float var2InCanvas = MainActivity.var2;
private float var3inCanvas = MainActivity.var3;

Related

How to pass the value of variables from inside an override method to outside it in Android studio

I am having trouble, measuring the height and width of a programatically created LinearLayout in android studio, I adopted the following solution
Public class MainActivity extends AppCompatActivity {
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout layout = new LinearLayout(context.this);
layout.post(new Runnable() {
#Override
public void run() {
int width = layout.getWidth();
int height = layout.getHeight();
}
}
}
the problem I am having is that I cant retrieve the value of these variables outside the override method. I have tried creating separate variables outside the override method like this
final LinearLayout layout = new LinearLayout(context.this);
final int width;
final int height;
layout.post(new Runnable() {
#Override
public void run() {
width = layout.getWidth();
height = layout.getHeight();
}
}
Log.d(TAG, "width is "+ width.ToString())
but even in this case width = 0 if called outside the override method. So my question is, is there a way to pass the value of variables outside an override method or is there a different way of measuring the height/width of a layout when it is called in an onCreate method
Declare Both width and height outside onCreate method
public class MainActivity extends AppCompatActivity {
int width;
int height;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout layout = new LinearLayout(context.this);
layout.post(new Runnable() {
#Override
public void run() {
width = layout.getWidth();
height = layout.getHeight();
}
});
}
}

can I show a dialog / popup when clicking a button inside fragment?

I have a problem when it will display a custom dialog, I mean the button that is in the fragment when I click will popup / dialog.
anyone help?
Fragment
public abstract class BaseFragment extends Fragment {
public Context context;
public Activity activity;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
//or
this.activity = (Activity) context;
}
}
Dialog
public class BaseDialog extends Dialog {
public Context context;
public Activity activity;
public LayoutInflater inflater;
public Window window;
public View decorView;
private final WindowManager.LayoutParams attributes;
public BaseDialog(Context context) {
super(context);
activity = (Activity) context;
this.context = context;
inflater = LayoutInflater.from(context);
window = getWindow();
//no title
assert window != null;
window.requestFeature(Window.FEATURE_NO_TITLE);
//auto dismiss dialog
setCanceledOnTouchOutside(true);
//decorView
decorView = window.getDecorView();
attributes = getWindow().getAttributes();
}
/**
* Transparency 0.0f - 1.0f
*
* #param f
*/
public void setDimAmount(float f) {
attributes.dimAmount = f;
getWindow().setAttributes(attributes);
}
/**
* #param gravity gravity
*/
public void setGravity(int gravity) {
window.setGravity(gravity);
}
/**
* dialog animation
*
* #param resId
*/
public void setAnimation(int resId) {
window.setWindowAnimations(resId);
}
/**
* custom view
*
* #param view
* #param width
* #param height
*/
public void setContentView(View view, int width, int height) {
super.setContentView(view);
window.setLayout(width, height);
}
}
PopupWindow
public class MyPopupWindow extends PopupWindow {
public MyPopupWindow(View contentView, int width, int height) {
super(contentView, width, height);
}
#Override
public void showAsDropDown(View anchor) {
if (Build.VERSION.SDK_INT >= 24) {
Rect rect = new Rect();
anchor.getGlobalVisibleRect(rect);
int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
setHeight(h);
}
super.showAsDropDown(anchor);
}
#Override
public void showAsDropDown(View anchor, int xoff, int yoff) {
if (Build.VERSION.SDK_INT >= 24) {
Rect rect = new Rect();
anchor.getGlobalVisibleRect(rect);
int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
setHeight(h);
}
super.showAsDropDown(anchor, xoff, yoff);
}
}
=== End ===
public class MyFragment extends BaseFragment {
public void onClick(View v) {
showDialog();
//or
showPup(v);
}
private void showDialog() {
new MyDialog(context).show();
new MyDialog(activity).show();
}
private void showPup(View v) {
MyPopupWindow popupWindow = new MyPopupWindow(v, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setTouchable(true);
popupWindow.setAnimationStyle(R.style.sealFragment_menu_animation);
popupWindow.showAsDropDown(view);
}
}

Cannot draw a circle with loading of the fragment

I am trying to draw circles in the canvas. Currently I can do it on button click, but I also need to do the same when the Fragment is loaded. Below is my Fragment code.
public class StepTwentyOneFragment extends Fragment {
private CanvasView customCanvas;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.step21_fragment, container, false);
customCanvas=(CanvasView)v.findViewById(R.id.signature_canvas);
final Button button1=(Button)v.findViewById(R.id.step18button1);
float radius=(customCanvas.getCanvasWidth()/2) - ((customCanvas.getCanvasWidth()/2)/100)*60;
customCanvas.drawCircle(radius);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.getId()==R.id.step18button1){
float radius=(customCanvas.getCanvasWidth()/2) - ((customCanvas.getCanvasWidth()/2)/100)*60;
customCanvas.drawCircle(radius);
Log.d("An_Width", "" + customCanvas.getCanvasWidth());
Log.d("An_Height" ,""+ customCanvas.getCanvasHeight());
v.setBackgroundResource(R.drawable.button_border_5);
button1.setTextColor(Color.WHITE);;
}
}
});
return v;
}
public static StepTwentyOneFragment newInstance() {
StepTwentyOneFragment f = new StepTwentyOneFragment();
Bundle b = new Bundle();
f.setArguments(b);
return f;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
Activity a = getActivity();
if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
Below is my Canvas code
public class CanvasView extends View {
public int width;
public int height;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
Context context;
private Paint mPaint;
private float mX, mY;
private static final float TOLERANCE = 5;
private int canvasHeight, canvasWidth;
private float radius;
public CanvasView(Context c, AttributeSet attrs) {
super(c, attrs);
context = c;
mPath = new Path();
mPaint = new Paint();
mPaint.setStrokeWidth(3);
mPaint.setColor(Color.CYAN);
}
// override onDraw
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mCanvas=canvas;
Drawable d = getResources().getDrawable(R.drawable.circle_1);
canvasHeight= canvas.getHeight();
canvasWidth= canvas.getWidth();
Log.d("Height - "," / "+canvas.getHeight());
Log.d("Width - "," / "+canvas.getWidth());
// DisplayMetrics displaymetrics = new DisplayMetrics();
// ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
// int height = displaymetrics.heightPixels;
// int width = displaymetrics.widthPixels;
float h=canvasHeight/2;
float w=canvasWidth/2;
d.setBounds(0, 0, canvasWidth, canvasHeight);
d.draw(canvas);
canvas.drawCircle(w, h, radius, mPaint);
}
public void clear2(){
radius=0;
//important. Refreshes the view by calling onDraw function
invalidate();
}
public void drawCircle(float radius1) {
radius=radius1;
//important. Refreshes the view by calling onDraw function
invalidate();
}
public int getCanvasHeight()
{
return canvasHeight;
}
public int getCanvasWidth()
{
return canvasWidth;
}
}
Now my problem is , cannot draw a circle with loading of the fragment . It means the circle cannot draw without button action . But I want to do it when the fragment is loading .
Have any ideas ?
Thank you.

Find out which item in ListView was swiped

I am trying to swipe a row in my ListView, identify its text and perform certain actions. I am able to detect left/right swipes but how to I go about identifying the text for that swiped row? I am not able to identify its location unlike using onItemClickListener where I could use the position variable.
MainActivity Class
ListView orderListView;
ArrayList<String> orders;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_stock);
orderListView = (ListView)findViewById(R.id.orderListView);
orders = new ArrayList<>();
orders.add("order 1");
orders.add("order 2");
orders.add("order 3");
adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, orders);
orderListView.setAdapter(adapter);
OnSwipeTouchListener onSwipeTouchListener = new OnSwipeTouchListener(this, orderListView);
orderListView.setOnTouchListener(onSwipeTouchListener);
}
OnSwipeTouchListener Class
public class OnSwipeTouchListener implements View.OnTouchListener {
ListView list;
private GestureDetector gestureDetector;
private Context context;
public OnSwipeTouchListener(Context ctx, ListView list) {
gestureDetector = new GestureDetector(ctx, new GestureListener());
context = ctx;
this.list = list;
}
public OnSwipeTouchListener() {
super();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
public void onSwipeRight(int pos) {
Log.i("zxR", "right");
}
public void onSwipeLeft() {
Log.i("zxL", "left");
}
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
#Override
public boolean onDown(MotionEvent e) {
return true;
}
private int getPostion(MotionEvent e1) {
return list.pointToPosition((int) e1.getX(), (int) e1.getY());
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
onSwipeRight(getPostion(e1));
else
onSwipeLeft();
return true;
}
return false;
}
}
}
Try this, I think this might help:
Include ArrayAdapter in the argument of the constructor of OnSwipeTouchListener and pass the adapter of the ListView from the main activity
Then add this code to your onFling()
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
int id = list.pointToPosition((int) e1.getX(), (int) e1.getY());
String text=adapter.getItem(id);
Toast.makeText(context,"Text:"+text,Toast.LENGTH_SHORT).show();
Use the new RecyclerView instead of ListView as it have simple api for gestures and animations.
The same question for RecyclerView:
https://stackoverflow.com/a/30601554/2627680

Can't assign type

I hame class GameManager(),
int class variable:
public GameView view;
it's class constructor:
public GameManager (GameView view)
{
this.view = view;
}
in the class GameView I create :
private GameManager gameLoopThread;
....
public GameView(Context context) {
super(context);
gameLoopThread = new GameView(this);// HERE IS ERROR ;
I dont know why it want to change gameLoopThread to GameView() type.
gameLoopThread = new GameManager(this);

Categories