I have a custom camera app which have a centered rectangle view, as you can see below:
When I take a picture I want to ignore everything outside the rectangle. The view hasn't any connection with the Camera Preview or SurfaceView in my XML view, as follows:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="#+id/preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView
android:id="#+id/cameraview"
android:name="com.kut.camera.KutCameraFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<View android:id="#+id/viewTamanho"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="400px"
android:layout_marginTop="300px"
android:layout_marginStart="70px"
android:layout_marginEnd="70px"
android:background="#drawable/border" />
<RelativeLayout
android:id="#+id/rel_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alpha="1"
android:background="#android:color/black"
android:orientation="vertical"
android:padding="10dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textViewReferan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Evidência"
android:textColor="#android:color/white"
android:textSize="16sp" />
<Button
android:id="#+id/button_exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#android:color/transparent"
android:text="Sair"
android:textColor="#2799CF" />
</RelativeLayout>
<LinearLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone" >
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/islem_value_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Carregando..." />
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:alpha="0.9"
android:background="#android:color/black"
android:padding="10dp" >
<ImageView
android:id="#+id/imageView_foto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/camera" />
<ImageView
android:id="#+id/imageView_photo"
android:layout_width="80dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:padding="5dp"
android:scaleType="fitCenter"
android:src="#drawable/fotoicon" />
</RelativeLayout>
</RelativeLayout>
</FrameLayout>
Can somebody help me how to crop the image properly? I tried to create a new Bitmap based on my XML but obviously it didn't work, something like:
Camera.PictureCallback jpegCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//.../
Bitmap imagemOriginal = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap imagemCortada = Bitmap.createBitmap(imagemOriginal, 70, 400, imagemOriginal.getWidth() - 70,
imagemOriginal.getHeight() - 400);
//.../
}
I put those initial values for x and y, and tried to subtract (based on XML values from View referring to marginTop, Bottom, etc...) from width and Height but I hadn't success because I don't know how to match View coordinates with the image coordinates taken from Camera. Also, it seems for me Bitmap.createBitmap does limited crop, apparently I can't crop it to a rectangle directly.
To control cropping, you must control the picture size and the rectangle size.
It is very important to a) choose the picture size with same aspect ratio as the preview, and b) make sure that the preview is not distorted on the screen. If you prepare your app for a wide range of devices, both tasks are not trivial. To achieve the latter, you need to control both preview size and the SurfaceView size. I have explained this in more detail elsewhere.
To keep it simple, I suggest to ignore the tablets that may have natural Landscape orientation. On phones, the captured image will be "rotated" 90° even if you set camera orientation to portrait (which only effects preview). Don't expect setRotation() to fix this for you: by the book, it is allowed to simply set the EXIF flag for the captured image.
You set the margins for viewTamanho in px. This may not scale well on variety of screens. I suggest setting the dimensions of this view programmatically, as certain percent of the preview surface. You can use support library to define this in XML, but I am afraid this will not give you enough control.
With all this at hand, let's say that we have preview of 1280×720, picture of 2560×1440, our screen is 1280×800, and the rectangle is in the middle, 616×400 pixels (which is more or less the size scaled from your screenshot).
The actual preview size on screen will be probably 1000x562, padded on the right and left with black margins of 79px. Then the following code will produce the expected captured picture:
public void onPictureTaken(byte[] data, Camera camera) {
//.../
Bitmap imagemOriginal = BitmapFactory.decodeByteArray(data, 0, data.length); // 2560×1440
float scale = 1280/1000F;
int left = (int) scale*(imagemOriginal.getWidth()-400)/2;
int top = (int) scale*(imagemOriginal.getHeight()-616)/2;
int width = (int) scale*400;
int height = (int) scale*616;
Matrix rotationMatrix = new Matrix();
rotationMatrix.postRotate(90);
Bitmap imagemCortada = Bitmap.createBitmap(imagemOriginal, left, top, width, height, rotationMatrix, false);
//.../
}
Here i used this
implementation 'com.otaliastudios:cameraview:2.6.2'
library for getting bitmap image after taking picture.
Here is the code how i achieved this
public void croppingRectangle (Bitmap bitmap, CameraView mCameraView, FrameLayout rectangle) {
int cameraHeight = mCameraView.getHeight();
int cameraWidth = mCameraView.getWidth();
DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int leftAndRightMarginsInPixels = Math.round(Math.round(getResources().getDimension(Your_dimens) * 2));`
here i did scaling, after taking picture
int left = (int) Math.round(((double)rectangle.getX()/(double)cameraWidth) * bitmap.getWidth();
int top = (int) Math.round(((double)rectangle.getY()/(double)cameraHeight) * bitmap.getHeight();
int width =
(int) (capturedWidth - Math.round(((double)leftAndRightMarginsInPixels / (double) displayMetrics.widthPixels) * bitmap.getWidth()));
int height = (int) Math.round(((double) rectangle.getHeight() / (double) displayMetrics.heightPixels) * bitmap.getHeight());
Matrix rotationMatrix = new Matrix();
rotationMatrix.postRotate(0);
Bitmap croppedImage = Bitmap.createBitmap(bitmap, left, top, width, height, rotationMatrix, false);
}
P.S : I have achieved 95% accuracy for top & bottom, 70% in getting width of a frame
Related
I'm writing a code for a school project where one has to load a data file (CSV file, text file, etc) and from the obtained data, the app will pass the data to a custom draw View and the onDraw method will draw/plot a graph based on the data.
My goal is for the app to display 2 graphs, one after the other (stacked). The first set of data is loaded and the 1st graph is drawn. The loaded data is then used for a different calculation in a different method. The custom draw View is then called again with the new data to draw the 2nd graph.
When I run the app, both charts are drawn but because the x and y-axis' of the graph are coded to be drawn at certain fixed pixels, the 2nd graph is drawn over the first one and therefore only the 2nd graph is visible.
Is there any way I can draw the 2 graphs so that it does not overlap and instead appears to be stacked in ScrollView?
My code is shown below but I've gotten rid of calculations that I think aren't very important. Any help and pointers would be very much appreciated!
MainActivity.java:
#Override
protected void onActivityResult(......) {
super.onActivityResult(......);
switch (1) {
case 1:
Graph graph = this.findViewById(R.id.graph1);
graph.setData(data); // the loaded data is passed to Graph View
Graph drawGraph2 = this.findViewById(R.id.graph2);
graph2.setData(this.newCalculate(data));
break;
}
}
Graph.java
public class Graph extends View {
private Paint mPaint = new Paint();
private final int zero = 700; // mark the 0 line of graph at 700 pixels
public void setData(data){
......
}
public Graph(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
#Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthSize, heightSize);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
plotUnit(canvas); // plot points on graph
axisLabel(canvas); // label axis
axisLine(canvas); // draw axis
xyAxisMarker(canvas); // mark axis
}
private void plotUnit(Canvas canvas) {
......
// Due to data having negative values, the graph is inverted and the 0 starts
// of the graph is defined at 700 pixels (private final int zero)
}
private void axisLabel(Canvas canvas) {
......
}
private void axisLine(Canvas canvas, int inset) {
......
}
private void xyAxisMarker(Canvas canvas) {
......
}
Update
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/loadbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Open Data File" />
<firstapp.drawtwograph.Graph
android:id="#+id/graph1"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<firstapp.drawtwograph.Graph
android:id="#+id/graph2"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
</ScrollView>
</LinearLayout>
You cannot have two views' heights match parent height inside of a LinearLayout with vertical orientation. It is not possible because heights of these views must be equal to the parent height but at the same time, they must be ordered one after the other resulting in double of parent's height.
If you imagine parent's height as 10dp then each of the Graph views must be 10dp as well which means parent's height must be 20dp, not 10dp. That is going to cycle forever so the Android does a simple thing: views that are going below the first child view with android:layout_height="match_parent" will have height 0dp or if their height is fixed they will be drawn outside of the layout and will not be visible.
Example
Screenshot from Design tab of layout editor in Android Studio IDE.
Here you can see:
red view as a parent linear layout;
purple view as a first child with height matching it's parent height;
outlined view that is drawn outside of the layout because it is pushed out by the first child with android:layout_height="match_parent";
there is one more view that is crushed to 0 height and thus not visible. You can see it down in the XML code.
XML code of this sample:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#android:color/holo_red_light">
<LinearLayout
android:background="#color/colorPrimary"
android:layout_width="60dp"
android:layout_height="match_parent" <!-- this view's height is a problem -->
android:orientation="vertical"/>
<LinearLayout
android:background="#android:color/holo_green_dark"
android:layout_width="120dp"
android:layout_height="match_parent" <!-- height is not fixed, then it will be 0 -->
android:orientation="vertical"/>
<LinearLayout
android:background="#android:color/holo_green_light"
android:layout_width="120dp"
android:layout_height="40dp" <!-- height is fixed, it is outlined outside of a layout -->
android:orientation="vertical"/>
</LinearLayout>
How to fix the issue?
Set fixed height. As a test try to define a fixed height, e.g. 100dp;
Redesign your layout. Use RelativeLayout or ConstraintLayout to position views relative to each other so that they are always visible no matter what the screen size, ratio, density is.
Example of how to fix
I personally prefer ConstraintLayout as it is very powerful in terms of positioning and adaptation.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/loadbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Open Data File"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<firstapp.drawtwograph.Graph
android:id="#+id/graph1"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/graph2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/loadbutton" />
<firstapp.drawtwograph.Graph
android:id="#+id/graph2"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/graph1" />
</androidx.constraintlayout.widget.ConstraintLayout>
The result is (I used two buttons instead of Graph views):
Hints:
If you want to use ScrollView then setting fixed height or defining height at runtime will be required.
Get rid of private final int zero = 700; // mark the 0 line of graph at 700 pixels. Do not use pixel values directly as it will lead to error-prone UI. It will be the case of "work on my phone, does not work the other". Use view's height as the 0 line.
I have a dialog popping up with a title and a close button. This is the XML:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical">
<TextView
android:id="#+id/text_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="24dp"
android:layout_marginRight="0dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:maxLines="1"
<!--- android:singleLine="true" <-- Do not comment about this, it is deprecated --->
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:textSize="20sp"
android:textColor="#android:color/black"
/>
<ImageView
android:id="#+id/backburger"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:src="#drawable/ic_close"
android:foreground="?android:attr/selectableItemBackground"
/>
</LinearLayout>
Like you can see the TextView has all the things it needs for a marquee, the singleLine options is deprecated, so I can't use it. I do call setSelected(true) in my Java. There are lots of questions about a marquee, but none with layout_weight and from '17.
This is the preview of the XML:
Try this one:
In your Xml:
<TextView
android:id="#+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:textSize="20sp"
android:textColor="#android:color/black" />
and your Code:
tv = (TextView) this.findViewById(R.id.text_title);
tv.setSelected(true);
Hope its help:)
public void setticker(String text, TextView view) {
if (text != "") {
view.setText(text);
//view.setTextSize(25.0F);
Context context = view.getContext(); // gets the context of the view
// measures the unconstrained size of the view
// before it is drawn in the layout
view.measure(View.MeasureSpec.UNSPECIFIED,
View.MeasureSpec.UNSPECIFIED);
// takes the unconstrained width of the view
float width = view.getMeasuredWidth();
float height = view.getMeasuredHeight();
// gets the screen width
float screenWidth = ((Activity) context).getWindowManager()
.getDefaultDisplay().getWidth();
// view.setLayoutParams(new LinearLayout.LayoutParams((int) width,
// (int) height, 1f));
System.out.println("width and screenwidth are" + width + "/"
+ screenWidth + "///" + view.getMeasuredWidth());
// performs the calculation
float toXDelta = width - (screenWidth - 0);
// sets toXDelta to -300 if the text width is smaller that the
// screen size
if (toXDelta < 0) {
toXDelta = 0 - screenWidth;// -300;
} else {
toXDelta = 0 - screenWidth - toXDelta;// -300 - toXDelta;
}
// Animation parameters
Animation mAnimation = new TranslateAnimation(screenWidth,
toXDelta, 0, 0);
mAnimation.setDuration(15000);
mAnimation.setRepeatMode(Animation.RESTART);
mAnimation.setRepeatCount(Animation.INFINITE);
view.setAnimation(mAnimation);
//parent_layout.addView(view);
}
}
I am making an Android app and attempting to programatically draw some clickable, rectangular blocks with text on one of two custom views contained in a ScrollLayout. The XML for my ScrollLayout looks like this:
<ScrollView
android:layout_width="match_parent"
android:id="#+id/calendarGridContainerView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_below="#+id/employeeSpinnerContainer"
android:paddingBottom="72dp"
android:layout_height="match_parent"
android:overScrollMode="never"
android:fillViewport="true"
android:elevation="1dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:id="#+id/schedule_view_container"
android:layout_height="wrap_content">
<FrameLayout
android:layout_height="wrap_content"
android:id="#+id/schedule_time_frame"
android:layout_width="100dp"
android:layout_alignParentTop="false"
android:layout_weight="0.5">
<include
layout="#layout/schedule_time_view"
android:layout_height="wrap_content"
android:layout_width="100dp" />
</FrameLayout>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/schedule_grid_frame"
android:minHeight="179dp"
android:layout_toRightOf="#+id/schedule_time_frame"
android:layout_centerHorizontal="false"
android:layout_weight="8">
<include
layout="#layout/schedule_grid_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</FrameLayout>
</LinearLayout>
</ScrollView>
Note that the layout called scheduleGridLayout is where I am trying to draw these rectangles. It has the following XML:
<?xml version="1.0" encoding="utf-8"?>
<(package).ScheduleGridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:scheduleGridLayout="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
</(package).ScheduleGridLayout>
(When copying the above code, I removed the package name.)
In the constructor for ScheduleGridLayout.java, I call this.setWillNotDraw(false);. Before drawing the rectangles, I draw some horizontal gridlines on ScheduleGridLayout through its overridden onDraw() method:
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.LTGRAY);
final int width = getWidth();
final int rowHeight = ScheduleTimeLayout.SCHEDULE_VIEW_ROW_HEIGHT + ScheduleTimeLayout.TIME_LABEL_HEIGHT;
for(int i = 0; i < ScheduleTimeLayout.TIME_SEGMENT_COUNT + 1; i++){
if ((i % (int)(1.0/ScheduleTimeLayout.SEGMENT_SIZE)) == 0){
paint.setColor(Color.GRAY);
paint.setStrokeWidth((float)4.0);
}
else{
paint.setColor(Color.LTGRAY);
paint.setStrokeWidth((float)2.0);
}
int y = 178 + (int)(i*(rowHeight + 1) - rowHeight/2.0);
canvas.drawLine(0, y, width, y, paint);
}
Since I want the rectangles to be clickable, I have to add them as some sort of views rather than simply drawing their images onto the canvas. I've tried a few different ways to draw the rectangles-- currently I try to do it in onFinishInflate() in ScheduleGridLayout.java, like so:
Bitmap bmp = Bitmap.createBitmap(60,200,Bitmap.Config.RGB_565);
Bitmap tempBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
paint = new Paint();
paint.setColor(Color.RED);
tempCanvas.drawBitmap(bmp, 0, 0, null);
tempCanvas.drawRoundRect(new RectF(0,0,600,600), 2, 2, paint);
ImageView testBlock = new ImageView(getContext());
testBlock.setImageDrawable(new BitmapDrawable(getResources(), tempBitmap));
addView(testBlock);
However, there the block does not appear when I do this.
In a separate attempt, I tried creating an XML layout file for the schedule block:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<com.dalc.dalccalendar.ScheduleBlock
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:scheduleGridLayout="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/schedule_block">
</com.dalc.dalccalendar.ScheduleBlock>
In ScheduleBlock.java, I override onMeasure() to set the size of the block using setMeasuredDimension, and I override onDraw() with the following code:
super.onDraw(canvas);
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
canvas.drawPaint(paint);
String bgColor = "#FF0000";
setBackgroundColor(Color.parseColor(bgColor));
I noticed that red rectangle does appear in the XML file's preview, but not when I try to add the block in ScheduleGridLayout:
FrameLayout blockFrame = (FrameLayout)LayoutInflater.from(getContext()).inflate(R.layout.schedule_block_container, this, false);
testBlock.setElevation(4);
addView(blockFrame);
Not only does the rectangle not appear when I run the app, but I've found that the onDraw() method for ScheduleBlock is not called. What am I doing wrong? How can I make these blocks appear inside my scrollview on top of the gridlines and be interactable with clicks? I'd prefer to be able to do with with custom views if possible, since each block needs to be associated with specific data.
I have a problem and I can't solve it, I will appreciate it if somebody would help me. I want to put two images on the top of the screen. Both images should have width = screen_width/2 (just because when the screen is smaller, images should resize).I've tried this, but it isn't enough. Thank you!
<RelativeLayout
android:id="#+id/imagelayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/r"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="3dp"
android:background="#drawable/back" />
<TextView
android:id="#+id/resulttext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textStyle="bold"
android:text="Hello"
android:layout_alignLeft="#id/r"
android:layout_alignTop="#id/r"
android:layout_alignRight="#id/r"
android:layout_alignBottom="#id/r"/>
</RelativeLayout>
For reference : http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&ved=0CC0QtwIwAg&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DmlojNcvoW68&ei=RoX4U8zwLdbvaKmOgMgH&usg=AFQjCNE5rRlHfVw-n_jgZAXEhK-Q1dd_Mg&sig2=mt8454k4FzqoVBprIqorNg&bvm=bv.73612305,d.d2s
<RelativeLayout //Change this to a linear layout
android:id="#+id/imagelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="2" > //add this to linear layout attribute
<ImageView
android:id="#+id/r"
android:layout_width="0dp" //change width to 0dp (in case of horzontal layout)
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="3dp"
android:background="#drawable/back"
android:layour_weight = "1"/> //add this to both view
<TextView
android:id="#+id/resulttext"
android:layout_width="0dp" //change width to 0dp (in case of horzontal layout)
android:layout_height="wrap_content"
android:textSize="30sp"
android:textStyle="bold"
android:text="Hello"
android:layout_alignLeft="#id/r"
android:layout_alignTop="#id/r"
android:layout_alignRight="#id/r"
android:layout_alignBottom="#id/r"
android:layour_weight = "1"/> //add this to both view/>
</RelativeLayout> //This again has to be linear layout
Use LinearLayout instead/inside RelativeLayout and set the weight property to 0.5 in each child view. you should also use layout:gravity to set the child view on the top.
Try this:
private int columnWidth;
//get Screen Size
public int getScreenWidth() {
int columnWidth ;
WindowManager wm = (WindowManager) this
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
//set height and width of Imageview
int height=columnWidth;
int width=columnWidth;
img.setLayoutParams(new RelativeLayout.LayoutParams(height,width));
Hope this may help you
I need to apply a translation animation to an ImageView, this ImageView is positioned at certain place and i need to animate it to the center of the screen. Here is my translate xml code, but it doesn't animate the ImageView to the center.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="500"
android:fromXDelta="0%p"
android:fromYDelta="0%p"
android:toXDelta="50%p"
android:toYDelta="50%p" />
</set>
This is the XML where the ImageView is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/WelcomeLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/welcome_background"
android:orientation="vertical" >
<ImageView
android:id="#+id/welcome_innovaLogo"
android:layout_width="300dp"
android:layout_height="150dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="1dp"
android:layout_marginTop="5dp"
android:contentDescription="#string/welcome_innovaLogoString"
android:scaleType="fitXY"
android:src="#drawable/innova_logo" >
</ImageView>
<TextView
android:id="#+id/welcome_innovaInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/welcome_innovaLogo"
android:layout_marginTop="20dp"
android:layout_toRightOf="#+id/welcome_innovaLogo"
android:text="#string/welcome_innovaInfoString"
android:textColor="#9acd32"
android:textStyle="bold" />
<TextView
android:id="#+id/welcome_innovaHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/welcome_innovaInfo"
android:layout_marginRight="20dp"
android:text="#string/welcome_innovaHeaderString"
android:textColor="#9acd32"
android:textSize="20sp"
android:textStyle="italic" />
<ListView
android:id="#+id/welcome_commandsListView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/welcome_innovaLogo"
android:layout_marginTop="40dp"
android:cacheColorHint="#00000000" />
<LinearLayout
android:id="#+id/welcome_loadingLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="450dp"
android:orientation="horizontal"
android:visibility="invisible" >
<ProgressBar
style="?android:attr/progressBarStyleSmall"
android:layout_width="50dp"
android:layout_height="50dp"
android:indeterminateDrawable="#drawable/progress_large" />
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:text="Loading Data..."
android:textColor="#color/green_color"
android:textSize="19sp" >
</TextView>
</LinearLayout>
<!--
<fragment
android:id="#+id/welcome_facebookFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/welcome_innovaLogo"
android:layout_marginLeft="20dp"
android:layout_marginTop="?android:attr/actionBarSize"
android:layout_toRightOf="#+id/welcome_commandsListView"
class="innovaEgypt.com.Welcome.FacebookFragment" >
</fragment>
-->
Have a look at this question. I gave a similar answer but the animation is not from an xml but from code. Hope it helps.
EDIT:
Your problem is that the animation doesn't take into account the image dimensions. The animation is centering the origin coordinate of your ImageView.
I still suggest my solution.
I tried the code in the answer that I linked and it works. Just copy this function:
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.WelcomeLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
and call it passing your view as the parameter:
ImageView img1 = (ImageView) findViewById( R.id.welcome_innovaLogo );
moveViewToScreenCenter(img1);
If your image still disappear, maybe is because it is behind your other widgets, like the ListView. If that is the case, reestructure your xml layout definig the ImageView at the end, just after the Listview (just cut and paste the ImageView).
For future updates...
Apply view property animation to move position of widget. Image view in this case
int layoutWidth = parentLayout.getWidth();
layoutWidth = ((int) layoutWidth / 2) - (imageView.getWidth()) ;
Log.d(TAG, " position - " + layoutWidth);
imageView.animate()
.translationX(-layoutWidth)
.translationY(0)
.setDuration(500)
.setInterpolator(new LinearInterpolator())
.start();
Try adding delay to this code.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
moveViewToScreenCenter( view );
}
},
1000);