i have to implement a custom dialog that should look like this and should have a special position, like i need to attach it to some component.
Could you be so kind to give me some implementation ideas?
I was thinking about overwriting the existing Android Dialog component but i am not sure i can achieve this functionality just like that.
Any link reference or idea is highly appreciated.
make a class which is subclass of Dialog class and set your custom view by setContentView in it, this will make your code bit cleaner. see the sample over here
How to create a Custom Dialog box in android?
all you need to do is create an XML exactly like you would any other layout and inflate it.
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//here is where you inflate your XML for the dialog
dialog.setContentView(R.layout.your_dialog_xml);
//now you can grab a reference to any component in your given xml like this
Button exampleButton = (Button) dialog.findViewById(R.id.my_xml_button);
//add any listeners etc.
//display your dialog
dialog.show();
I have had a simmillar requirement , hope this helps. ::
CUSTOM DIALOG CLASS
public class CustomDialogShape extends View {
public int startPointY,startPointX;
public int windowWidth;
public int dialogWidth, dialogHeight;
public int leftTop, rightTop;
public CustomDialogShape(Context context) {
super(context);
}
/**
*
* #param XPos
* #param YPos
* #param windowWidth
* #param dialogHeight
* #param dialogWidth
* Get the Click position, dialog dimension and window width from the parent window
* calculate the co-ordinates to draw the custom dialog shape
*/
public void setDimension(int XPos, int YPos, int windowWidth, int dialogHeight, int dialogWidth) {
this.startPointY = YPos;
this.startPointX = XPos;
this.windowWidth = windowWidth;
this.dialogHeight = dialogHeight;
this.dialogWidth = dialogWidth;
if(startPointX <= (windowWidth/2)) {
//Start Position is on the left half of the Screen
if(startPointX < (dialogWidth/2)) {
//Start position is on the leftmost end.
leftTop = 10;
rightTop = leftTop + dialogWidth;
} else {
leftTop = startPointX - (dialogWidth/2);
rightTop = leftTop + dialogWidth;
}
} else {
int rightSideRemaining = windowWidth - startPointX;
if(rightSideRemaining < (dialogWidth/2)) {
//Start position is on the leftmost end.
rightTop = windowWidth - 10;
leftTop = rightTop - dialogWidth;
} else {
rightTop = startPointX + (dialogWidth/2);
leftTop = rightTop - dialogWidth;
}
}
}
public CustomDialogShape(Context context, AttributeSet at) {
super(context, at);
}
/**
* Fill and Stroke Color
*/
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// custom drawing code here
// remember: y increases from top to bottom
// x increases from left to right
Paint paint = new Paint();
paint.setColor(Color.BLACK);
canvas.drawPath(drawCustomShape(startPointX, startPointY, leftTop, rightTop), paint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
paint.setColor(Color.GRAY);
canvas.drawPath(drawCustomShape(startPointX, startPointY, leftTop, rightTop), paint);
}
private Path drawCustomShape(int startPointX, int startPointY, int leftTop, int rightTop) {
Path pathFill = new Path();
pathFill.moveTo(startPointX, startPointY);
pathFill.lineTo(startPointX - 10, startPointY + 10);
pathFill.lineTo(leftTop, startPointY + 10);
pathFill.lineTo(leftTop, startPointY + 10 + dialogHeight);
pathFill.lineTo(rightTop, startPointY + 10 + dialogHeight);
pathFill.lineTo(rightTop, startPointY + 10);
pathFill.lineTo(startPointX + 10, startPointY + 10);
pathFill.lineTo(startPointX, startPointY);
pathFill.close();
return pathFill;
}
MyLAYOUT.XML
<?xml version="1.0" encoding="utf-8"?>
<com.cablevision.optimum2.widget.CustomDialogShape
android:id="#+id/custom_shape"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#android:color/transparent" />
<LinearLayout
android:id="#+id/list_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginLeft="100dip"
android:orientation="vertical" >
<ListView
android:id="#+id/stb_listVals"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="40dip"
android:clickable="false"
android:divider="#AA000000"
android:dividerHeight="7.3dip"
android:focusable="false"
android:scrollbarThumbVertical="#drawable/login_help_thumb"
android:scrollbarTrackVertical="#drawable/login_help_track"
android:scrollbars="vertical" >
</ListView>
</LinearLayout>
</FrameLayout>
IN MY CODE
Rect r = locateView(activity.findViewById(View_where_you_touch));
float touchX= //get the touchx position by calculating through r.leftand r.right);
float touchY=r.bottom;
final Dialog dialog = new Dialog(Ctxt,
android.R.style.Theme_Translucent_NoTitleBar);
dialog.getWindow().
setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
dialog.setContentView(R.layout.MyLAYOUT);
CustomDialogShape custom = (CustomDialogShape) chnSTBDialog
.findViewById(R.id.custom_shape);
custom.setDimension( touchX, touchY, custom_shape_width,
custom_shape_height , totalwindowWidth));
public static Rect locateView(View view) {
Rect loc = new Rect();
int[] location = new int[2];
if (view == null) {
Logging.e(TAG, "locateView", "View not found");
}
In the myLAYOUT XML I had my own list, you can make change to the contents for you needs like it can be linear layouts. Hope this helps
You can construct a custom Dialog like follows:
Dialog mDialog;
mDialog = new Dialog(YourActivityName.this);
mDialog.setContentView(R.layout.checklist_navigatepop);//XML layout file
mDialog.setTitle("Navigation alert");
mDialog.setCancelable(true);
mDialog.show();
Button bt = (Button) mDialog.findViewById(R.id.button3);
Button bt1 = (Button) mDialog.findViewById(R.id.button2);
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onBackPressed();
mDialog.dismiss();
}
});
Your don't need extends Dialog class.
You need something like this.
public Dialog buildDialog() {
Dialog messageDialog = new Dialog(context, android.R.style.Theme_Translucent);
messageDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set your custom layout here.
messageDialog.setContentView(R.layout.dialog_wifi_disabled);
// Don't let the user cancel the dialog.
messageDialog.setCancelable(false);
messageDialog.setCanceledOnTouchOutside(false);
// You can get the views, like this.
TextView textView = (TextView) messageDialog.findViewById(R.id.your_view);
}
More info here
Related
I have Create popup.xml and I want to load my webpage in WebView from assets folder.
Here is my popup.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/pp"
android:orientation="vertical" >
<WebView
android:id="#+id/webview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Here is my activity file
How to load my webpage in webview with popup window?
Is there any solution?
public class MainActivity extends ActionBarActivity {
Point p;
public int a, b, c, d;
ImageButton au, gc, cert, busa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
au = (ImageButton) findViewById(R.id.au);
gc = (ImageButton) findViewById(R.id.gc);
cert = (ImageButton) findViewById(R.id.cert);
busa = (ImageButton) findViewById(R.id.busa);
au.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (p != null) {
showPopup(MainActivity.this, p);
}
}
});
}
// Get the x and y position after the button is draw on screen
// (It's important to note that we can't get the position in the onCreate(),
// because at that stage most probably the view isn't drawn yet, so it will
// return (0, 0))
#Override
public void onWindowFocusChanged(boolean hasFocus) {
int[] location = new int[2];
// Get the x, y location and store it in the location[] array
// location[0] = x, location[1] = y.
// Initialize the Point with x, and y positions
p = new Point();
p.x = location[0];
p.y = location[1];
}
// The method that displays the popup.
private void showPopup(final Activity context, Point p) {
int popupWidth = 720;
int popupHeight = 380;
// Inflate the popup_layout.xml
LinearLayout viewGroup = (LinearLayout) context
.findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow(context);
popup.setContentView(layout);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setFocusable(true);
// Some offset to align the popup a bit to the right, and a bit down,
// relative to button's position.
int OFFSET_X = 130;
int OFFSET_Y = 100;
// Clear the default translucent background
// popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y
+ OFFSET_Y);
// Getting a reference to Close button, and close the popup when
// clicked.
}
}
Webview
webview1.loadURL("the url goes here");
I want to add some LinearLayouts to an existing Linearlayout.
The xml of the Activity looks as followed:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popupLinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPopUp"
android:gravity="center"
android:orientation="vertical" >
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none" >
<LinearLayout
android:id="#+id/ll_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
The code of the Activity:
public class MainActivity extends Activity {
private Point p;
private PopupWindow popup;
private LinearLayout myLInearLayout;
private TextView valueTV;
private Button valueB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button popUpButton = (Button) findViewById(R.id.open);
popUpButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (p != null)
showPopup(MainActivity.this, p);
}
});
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
int[] location = new int[2];
Button button = (Button) findViewById(R.id.open);
button.getLocationOnScreen(location);
// Initialize the Point with x, and y positions
p = new Point();
p.x = location[0];
p.y = location[1];
}
// The method that displays the popup.
private void showPopup(final Activity context, Point p) {
Rect rectgle = new Rect();
Window window = getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int popupWidth = this.getResources().getDisplayMetrics().widthPixels;
int popupHeight = this.getResources().getDisplayMetrics().heightPixels / 4;
// Inflate the popup_layout.xml
LinearLayout viewGroup = (LinearLayout) context
.findViewById(R.id.popupLinearLayout);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);
// Creating the PopupWindow
popup = new PopupWindow(context);
popup.setContentView(layout);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setOutsideTouchable(true);
popup.setFocusable(true);
popup.setAnimationStyle(R.style.PopupWindowAnimation);
// Some offset to align the popup a bit to the right, and a bit down,
// relative to button's position.
int OFFSET_X = 0;
int OFFSET_Y = 0;
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y
+ OFFSET_Y);
// add LInearLayout
myLInearLayout = (LinearLayout) findViewById(R.id.ll_horizontal);
// add LayoutParams
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT);
myLInearLayout.setOrientation(LinearLayout.HORIZONTAL);
// add textView
valueTV = new TextView(this);
valueTV.setText("The developer world is yours");
valueTV.setId(5);
valueTV.setLayoutParams(params);
// add Button
valueB = new Button(this);
valueB.setText("thedeveloperworldisyours");
valueB.setId(5);
// add the textView and the Button to LinearLayout
myLInearLayout.addView(valueTV);
myLInearLayout.addView(valueB);
}
#Override
public void onBackPressed() {
if (popup != null && popup.isShowing()) {
popup.dismiss();
popup = null;
} else {
super.onBackPressed();
}
}
As you can see I want to add a Button and a TextView after I inflate a View and show it with an Animation in a PopupWindow. I would like to add some Views to the LinearLayout inside the ScrollView. This is for testing purposes, later I want to Add full LinearLayouts to the LinearLayout inside the ScrollView.
The Animation works perfectly. I just can't add some Views programmatically. Everything I get is a NullPointerException in the Line where I try to add the views.
I appreciate your help.
Try this way,hope this will help you to solve your problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button popUpButton = (Button) findViewById(R.id.open);
int[] location = new int[2];
popUpButton.getLocationOnScreen(location);
// Initialize the Point with x, and y positions
p = new Point();
p.x = location[0];
p.y = location[1];
popUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (p != null)
showPopup(p);
}
});
}
// The method that displays the popup_layout.
private void showPopup(Point p) {
Rect rectgle = new Rect();
Window window = getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int popupWidth = this.getResources().getDisplayMetrics().widthPixels;
int popupHeight = this.getResources().getDisplayMetrics().heightPixels / 4;
// Inflate the popup_layout.xml
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.popupLinearLayout);
View layout = LayoutInflater.from(this).inflate(R.layout.popup_layout, viewGroup);
// Creating the PopupWindow
popup = new PopupWindow(this);
popup.setContentView(layout);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setOutsideTouchable(true);
popup.setFocusable(true);
// popup.setAnimationStyle(R.style.PopupWindowAnimation);
// Some offset to align the popup_layout a bit to the right, and a bit down,
// relative to button's position.
int OFFSET_X = 0;
int OFFSET_Y = 0;
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup_layout at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y + OFFSET_Y);
// add LInearLayout
myLInearLayout = (LinearLayout) layout.findViewById(R.id.ll_horizontal);
// add LayoutParams
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.MATCH_PARENT);
myLInearLayout.setOrientation(LinearLayout.HORIZONTAL);
// add textView
valueTV = new TextView(this);
valueTV.setText("The developer world is yours");
valueTV.setId(5);
valueTV.setLayoutParams(params);
// add Button
valueB = new Button(this);
valueB.setText("thedeveloperworldisyours");
valueB.setId(5);
// add the textView and the Button to LinearLayout
myLInearLayout.addView(valueTV);
myLInearLayout.addView(valueB);
}
I figured out how to do it. I just had to inflate the popup.xml to be able to get a reference to the LinearLayout I wanted to customize.
Here is the code if someone is facing the same problem:
public class MainActivity extends Activity {
private Point p;
private PopupWindow popup;
private Button popUpButton;
private TextView valueTV;
private Button valueB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
popUpButton = (Button) findViewById(R.id.open);
popUpButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (p != null)
showPopup(MainActivity.this, p);
}
});
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
int[] location = new int[2];
Button button = (Button) findViewById(R.id.open);
button.getLocationOnScreen(location);
// Initialize the Point with x, and y positions
p = new Point();
p.x = location[0];
p.y = location[1];
}
// The method that displays the popup.
private void showPopup(final Activity context, Point p) {
Rect rectgle = new Rect();
Window window = getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int popupWidth = this.getResources().getDisplayMetrics().widthPixels;
int popupHeight = this.getResources().getDisplayMetrics().heightPixels / 4;
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.popup_layout, null);
ViewGroup dlgView = (ViewGroup) contentView
.findViewById(R.id.ll_horizontal);
// Creating the PopupWindow
popup = new PopupWindow(context);
popup.setContentView(contentView);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setFocusable(true);
popup.setAnimationStyle(R.style.PopupWindowAnimation);
// Some offset to align the popup a bit to the right, and a bit down,
// relative to button's position.
int OFFSET_X = 0;
int OFFSET_Y = 0;
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// add textView
valueTV = new TextView(this);
valueTV.setText("The developer world is yours");
valueTV.setId(5);
// add Button
valueB = new Button(this);
valueB.setText("thedeveloperworldisyours");
valueB.setId(5);
// add the textView and the Button to LinearLayout
dlgView.addView(valueTV);
dlgView.addView(valueB);
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(popUpButton, Gravity.NO_GRAVITY, p.x + OFFSET_X,
p.y + OFFSET_Y);
}
}
I need help with creating a dynamic array of 4 EditTexts inside a pop-up window. The implementation of the pop-up window with the dynamically EditText will work great if the pop-up was it's own activity;however, a pop up should not have it's own activity but use the activity of the class that it is in. Can you please shed some light on this. I believe this has to deal with application context. Here is the code.
public class SideBucket extends Activity {
//The "x" and "y" position of the "Show Button" on screen.
private Point p;
private String[] _hold;
private LinearLayout viewGroup;
private TextView tv;
private View layout;
private EditText[] _edText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_side);
tv = (TextView) findViewById(R.id.textView1);
this.buttonActions();//explicit call to this class.
onPause();
}
#Override
protected void onPause(){
super.onPause();
buttonActions();
}
public void buttonActions(){
// Array for buttons that initially show up on the main Activity.
final Button[] b = {(Button) findViewById(R.id.button1), (Button) findViewById(R.id.side_next)};
for(int i=0;i<b.length;i++){
b[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//this button is in the main activity
and when pressed the popped out window shows up.
if(b[0].isPressed()){
//Open popup window
if(p != null)
{showPopup(SideBucket.this, p);}
//for(int t=0;t<_edText.length;t++){
//_edText[t].setText(_hold[t]);
//}
}//end of if statement
// this button is in the main activity
of the sideBucket mxl file and it switches intents.
if(b[1].isPressed()) {
Intent intent = new
Intent(SideBucket.this,FrontBucket.class);
startActivity(intent);
}
//end for view v
}});
}//for loop
}
// Get the x and y position after the button is draw on screen
// (It's important to note that we can't get the position in the onCreate(),
// because at that stage most probably the view isn't drawn yet, so it will return (0, 0))
#Override
public void onWindowFocusChanged(boolean hasFocus) {
int[] location = new int[2];
Button button = (Button) findViewById(R.id.button1);
// Get the x, y location and store it in the location[] array
// location[0] = x, location[1] = y.
button.getLocationOnScreen(location);
//Initialize the Point with x, and y positions
p = new Point();
p.x = location[0];
p.y = location[1];
}
public void showPopup(final Activity context, Point p) {
int popupWidth = 230;
int popupHeight = 330;
// Inflate the popup_layout.xml
viewGroup = (LinearLayout) context.findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = layoutInflater.inflate(R.layout.popup_layout,viewGroup);
//===============================//
//sets dimensions
LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
//goal how can we get layout to view the editText
_edText = new EditText[4];
for (int i = 0;i< _edText.length;i++) {
_edText[i] = new EditText(getApplicationContext());
btn[i].setText(btn[i].toString());
// _edText[i].setTextColor(Color.parseColor("#000000"));// why is the color parsed
_edText[i].setLayoutParams(param);
viewGroup.addView(_edText[i]);
viewGroup.addView(_edText[i]);
}
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow(layout,350,350,true); // context argument was taken out of this method.
popup.setContentView(layout);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setFocusable(true);
// Some offset to align the popup a bit to the right, and a bit
down, relative to button's position.
int OFFSET_X = -100;
int OFFSET_Y = 100;
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y
+ OFFSET_Y);
//Refference to editText in popup in an array.
// this array should be changed later on to create something more
dynamically robust.
//========================================================//
//Button calculate = (Button) layout.findViewById(R.id.close_calc);
//button inside of pop-up layout.
//calculate.setOnClickListener(new OnClickListener() {
// #Override
// public void onClick(View v) {
// _hold = new String[4];
// for(int i=0;i<_hold.length;i++){
// _hold[i] = _edText[i].getText().toString();
// }
// tv.setText("Result1:"+_hold[0]+"\n"+"Result2:"+_hold[1]+"
\n"+"Result3:"+_hold[2]+"\n"+"Result4:"+_hold[3]);
// popup.dismiss();
//}
//});
}
}
Hi I am creating a custom view in android.I have a LinerarLayout to which I am adding the custom views.I manage to add one custom view programmatically but if I add another it's not getting added into the layout.I don't know where am going wrong.My Main activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout container = (LinearLayout) findViewById(R.id.container);
final MyAnimationView animView = new MyAnimationView(this);
container.addView(animView);
final MyAnimationView animView1 = new MyAnimationView(this);
container.addView(animView1);
}
and my custom view class
public class MyAnimationView extends TextView implements ValueAnimator.AnimatorUpdateListener {
public final ArrayList<ShapeHolder> balls = new ArrayList<ShapeHolder>();
AnimatorSet animation = null;
private float mDensity;
public MyAnimationView(Context context) {
super(context);
mDensity = getContext().getResources().getDisplayMetrics().density;
ShapeHolder ball0 = addBall(75f, 400f);
}
public MyAnimationView(Context context,float x,float y) {
super(context);
mDensity = getContext().getResources().getDisplayMetrics().density;
ShapeHolder ball0 = addBall(105f, 400f);
}
private void createAnimation() {
if (animation == null) {
ObjectAnimator anim0=ObjectAnimator.ofFloat(balls.get(0),"y",getHeight(),500f).setDuration(500);
animation = new AnimatorSet();
animation.playTogether(anim0);
anim0.addUpdateListener(this);
}
}
private ShapeHolder addBall(float x, float y) {
OvalShape circle = new OvalShape();
circle.resize(100f * mDensity, 100f * mDensity);
ShapeDrawable drawable = new ShapeDrawable(circle);
ShapeHolder shapeHolder = new ShapeHolder(drawable);
shapeHolder.setX(x - 25f);
shapeHolder.setY(y - 25f);
int red = (int)(100 + Math.random() * 155);
int green = (int)(100 + Math.random() * 155);
int blue = (int)(100 + Math.random() * 155);
int color = 0xff000000 | red << 16 | green << 8 | blue;
Paint paint = drawable.getPaint(); //new Paint(Paint.ANTI_ALIAS_FLAG);
int darkColor = 0xff000000 | red/4 << 16 | green/4 << 8 | blue/4;
RadialGradient gradient = new RadialGradient(37.5f, 12.5f,
50f, color, darkColor, Shader.TileMode.CLAMP);
paint.setShader(gradient);
shapeHolder.setPaint(paint);
balls.add(shapeHolder);
return shapeHolder;
}
#Override
protected void onDraw(Canvas canvas) {
for (int i = 0; i < balls.size(); ++i) {
ShapeHolder shapeHolder = balls.get(i);
canvas.save();
canvas.translate(shapeHolder.getX(), shapeHolder.getY());
shapeHolder.getShape().draw(canvas);
canvas.restore();
}
}
public void startAnimation() {
createAnimation();
animation.start();
}
public void onAnimationUpdate(ValueAnimator animation) {
invalidate();
}
}
EDIT:here is my linear layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="#+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
any help will be greatly appreciated.
Just an assumption, donĀ“t know if it works. Try to do this in Your main:
LinearLayout container = (LinearLayout) findViewById(R.id.container);
final MyAnimationView animView = new MyAnimationView(this);
animView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.
WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
container.addView(animView);
final MyAnimationView animView1 = new MyAnimationView(this);
animView1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.
WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
container.addView(animView1);
does it work?
No it will be added but you can't see it. because your first view will take the full space of your screen. And your second will be added in below of your first view so it will be hidden from visible part of your device. I also met the same problem. I solved this with two layouts. see here for my solution.
I assume this is the problem that is why I provided this solution if not kindly let me know..
I have searched a great deal and have not found a solution to my problem. When I create multiple views and try to add them to a LinearLayout only the first view (cake) displays.
Here is where I create and add the views.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.image_View);
PlayAreaView cake = new PlayAreaView(SecondTestActivity.this, R.drawable.cake);
views.add(cake);
PlayAreaView bomb = new PlayAreaView(SecondTestActivity.this, R.drawable.bomb);
views.add(bomb);
PlayAreaView crown = new PlayAreaView(SecondTestActivity.this, R.drawable.crown);
views.add(crown);
PlayAreaView scissors = new PlayAreaView(SecondTestActivity.this, R.drawable.cut);
views.add(scissors);
PlayAreaView trash = new PlayAreaView(SecondTestActivity.this, R.drawable.bin_closed);
views.add(trash);
PlayAreaView key = new PlayAreaView(SecondTestActivity.this, R.drawable.bullet_key);
views.add(key);
LayoutParams params
= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for(View v : views){
Log.v("created", "view created");
v.setLayoutParams(params);
linearLayout.addView(v);
}
}
Here is my main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_View"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/image_View"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</FrameLayout>
I can create a single view and be fine but I am unable to add multiple views the the LinearLayout. Why is this?
If you look here, there was another person with basically the same problem. However, they were not declaring the orientation of their layout so it defaulted to horizontal. In your layout you have explicitly declared horizontal. Is this intended (for example to have the items show up side-by-side)? If not, change the orientation to vertical and you should be good.
If you need them to show side-by-side, then I am not sure off the top of my head how to do that, but I would guess you need to declare each view as next to the view placed before it (e.g. using something like 'alignToRightOf'. Again, this is just a stab-in-the-dark but it may get you going on a correct path.
Hope this helps.
I found the answer to my problem. I did not fully understand how the Activity handled views. For me to draw multiple separate views I have to loop over each view that I add to an array and call an overridden draw method in the custom view. After I understood this I was able to create multiple views and add separate dragging functions on each view. Here's the code.
public class ThirdTestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout) findViewById(R.id.main_View);
layout.addView(new MyCircles(this));
}
private class MyCircles extends View{
private Context myContext;
private ArrayList<MyCircle> circles = new ArrayList<MyCircle>();
private int size = 10;
public MyCircles(Context context) {
super(context);
myContext = context;
addCircles();
}
private void addCircles(){
for (int i = 0; i < size; i++){
circles.add(new MyCircle(myContext, R.drawable.skullcrossbones, i * 40, 50));
}
}
#Override
protected void onDraw(Canvas canvas){
for (View v : circles){
v.draw(canvas);
}
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
int mouseX = (int)event.getX();
int mouseY = (int)event.getY();
MyCircle image = null;
for(MyCircle images : circles){
//Log.v("image checked X: " + images.imageX + ", Y: " + images.imageY, "checked");
// Is the event inside of this view?
if(images.getImageRect().contains((int)event.getX(), (int)event.getY()))
{
image = images;
}
}
if (image != null){
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
Log.v("touched down", "touched down at X: " + mouseX + ", Y: " + mouseY);
image.dragDistance = new Point(mouseX, mouseY);
bringToFront();
isSelected();
return true;
}
else if(event.getAction() == MotionEvent.ACTION_MOVE)
{
Log.v("move", "moving to X: " + mouseX + ", Y: " + mouseY);
image.dragDistance.set(mouseX, mouseY);
invalidate();
return true;
}
}
return super.onTouchEvent(event);
}
}
private class MyCircle extends View{
private int imageId;
private Drawable image;
private Context myContext;
private int size = 48;
private int imageOffset = size/2;
private int imageX;
private int imageY;
private Point dragDistance;
public MyCircle(Context context, int id, int x, int y) {
super(context);
myContext = context;
imageId = id;
imageX = x;
imageY = y;
dragDistance = new Point(imageX + imageOffset, imageY + imageOffset);
}
public Rect getImageRect(){
return image.getBounds();
}
#Override
public void draw(Canvas canvas) {
//Log.v("draw","drawn");
super.onDraw(canvas);
image = myContext.getResources().getDrawable(imageId);
imageX = (dragDistance.x - imageOffset);
imageY = (dragDistance.y - imageOffset);
image.setBounds(imageX, imageY, imageX + size, imageY + size);
image.draw(canvas);
}
}
}
This is written for Android version 2.1 API 7