I have got custom class which is extending ViewGroup class. Inside it I want to add some views including two buttoons which has to be next to each other. I came up with idea of creating XML file with this view and then add it using addView. Unfortunately it doesn't work out.
My second idea, which I think is better was creating LineraLayout programmatically along with two buttons, setting up all the settings and then adding.
This is the code:
//adding view to view group
addView(createView(ctx));
//function creating linearlayout and buttons
private View createView(Context ctx){
LinearLayout l = new LinearLayout(ctx);
l.setOrientation(LinearLayout.HORIZONTAL);
l.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
Button btnL = new Button(ctx);
btnL.setText("Text1");
Button btnR = new Button(ctx);
btnR.setText("Text2");
l.addView(btnL);
l.addView(btnR);
return l;
}
The problem is, that I don't see this view now at all. I mean this created from LinearLayout. There is no error in LogCat.
Can someone please tell me what I have to do to add it?
EDIT:
This is code for onLayout, I don't have onMeasure:
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int w = getWidth();
int h = getHeight();
for (int i = 0; i < NUM_CHILDREN; i++) {
View v = getChildAt(i);
int ii = i * 4;
float fl = w * COORDS[ii] / GRID_WIDTH;
float ft = h * COORDS[ii + 1] / GRID_HEIGHT;
float fr = fl + w * COORDS[ii + 2] / GRID_WIDTH;
float fb = ft + h * COORDS[ii + 3] / GRID_HEIGHT;
v.layout(Math.round(fl), Math.round(ft), Math.round(fr),
Math.round(fb));
}
}
In general I am just using huge table where I have got info what exact dimensions of given view should be.
override your custom ViewGroup's onMeasure() like this:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int w = getWidth();
int h = getHeight();
for (int i = 0; i < NUM_CHILDREN; i++) {
View v = getChildAt(i);
int ii = i * 4;
float fw = w * COORDS[ii+2] / GRID_WIDTH;
float fh = h * COORDS[ii+3] / GRID_HEIGHT;
int wSpec = MeasureSpec.makeMeasureSpec(Math.round(fw), MeasureSpec.EXACTLY);
int hSpec = MeasureSpec.makeMeasureSpec(Math.round(fh), MeasureSpec.EXACTLY);
Log.d(TAG, "onMeasure Width " + MeasureSpec.toString(wSpec) + ", Height " + MeasureSpec.toString(hSpec));
v.measure(wSpec, hSpec);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
For your first idea I am giving you a example from my project as you asked.
It is based on a simple idea. I have an element designed in xml layout file. I load it from xml layout file. I change few things and finally I add it to an element that is currently being viewed on screen.
RelativeLayout relativeLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.android_messenger_sent_message, null);
TextView inbox_message = (TextView)relativeLayout.findViewById(R.id.sentMessage);
inbox_message.setText(conversationInfo.getBody());
TextView inbox_messageStatus = (TextView) relativeLayout.findViewById(R.id.sentMessageStatus);
String dateStatus = getDateForStatus(conversationInfo.getDateSent());
inbox_messageStatus.setText(""+dateStatus+" "+getString(R.string.me));
linearLayoutGlobal.addView(relativeLayout,0);
XML layout file from here below.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="2dp"
android:src="#drawable/contact_ico" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#+id/imageView1"
android:background="#color/light_blue"
android:orientation="vertical">
<TextView
android:id="#+id/sentMessageStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12:59, FirstName LastName"
android:textColor="#android:color/darker_gray"
android:paddingBottom="5dp"/>
<TextView
android:id="#+id/sentMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a long sample message and what if it will be toooooooo long?"
/>
</LinearLayout>
</RelativeLayout>
Related
I have a LinearLayout which is centered on the screen. It has a width less than the screen width. There are two buttons: Right-Arrow and Left-Arrow.
When the user presses the relevant button, the layout should increase its width from the relevant side. The other side should keep its position there.
Right now setting the width increases the layout from both sides equally. The layout needs to be initially centered and it has to expand from either side by user's input. (Use case is to find the width of relevant part of an image whose right and left sides have unequal borders, so the user has to mark them using my technique).
I am using following to increase width but it has the behaviour described above.
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)
llCropOverlay.getLayoutParams();
params.width = params.width + 1;
PS: This functionality was implemented in Tasker app since its early days; so it is possible.
EDIT:
Here is the layout.
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:gravity="top"
android:layout_gravity="top"
android:id="#+id/iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible" />
<LinearLayout
android:id="#+id/llRightLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<Button
android:id="#+id/bLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LEFT" />
<Button
android:id="#+id/bRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RIGHT" />
</LinearLayout>
<LinearLayout
android:layout_gravity="center_horizontal"
android:id="#+id/llCropOverlay"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="#color/colorCropOverlay"
android:orientation="vertical" />
</FrameLayout>
</LinearLayout>
The last LinearLayout (llCropOverlay) should be resized. Note that I am programatically changing the width to 300 before using resizing the buttons so I can test if the buttons are working.
I have found an almost perfect solution (there is sometimes a problem with one pixel which is annoying - any suggestions will be appreciated).
For this, we need some variables set up. Firstly, the LinearLayout called llCropOverlay must be found and identified.
Here is its xml:
<LinearLayout
android:layout_gravity="center_horizontal"
android:id="#+id/llCropOverlay"
android:layout_width="200dp"
android:layout_height="150dp"
android:background="#color/colorCropOverlay"
android:orientation="vertical" />
Now before allowing user to interact we need to find the original position of the llCropOverlay. So use this in OnCreate():
llCropOverlay.post(new Runnable() {
#Override
public void run() {
orgX = llCropOverlay.getX();
}
});
Now set up all the buttons and set a setOnTouchListener() on these buttons. Then when the listener is called, pass the touched button in the following method. Use a Handler and postDelayed() to keep calling this method till the button is pressed. Or call it once to resize by one pixel row/column.
void handleTouchOrClick(View view) {
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)
llCropOverlay.getLayoutParams();
switch (view.getId()) {
case R.id.bUp:
params.height = params.height - 1;
break;
case R.id.bDown:
params.height = params.height + 1;
break;
case R.id.bRight:
params.width = params.width + 1;
llCropOverlay.post(new Runnable() {
#Override
public void run() {
llCropOverlay.setX(orgX);
}
});
break;
case R.id.bRightContract:
params.width = params.width - 1;
llCropOverlay.post(new Runnable() {
#Override
public void run() {
llCropOverlay.setX(orgX);
}
});
break;
case R.id.bLeft:
params.width = params.width + 1;
orgX--;
llCropOverlay.post(new Runnable() {
#Override
public void run() {
llCropOverlay.setX(orgX);
}
});
break;
case R.id.bLeftContract:
params.width = params.width - 1;
orgX++;
llCropOverlay.post(new Runnable() {
#Override
public void run() {
llCropOverlay.setX(orgX);
}
});
break;
}
llCropOverlay.setLayoutParams(params);
}
Now here's how we actually resize the image:
For ease of users I am cropping it in two steps.
Crop from sides:
ViewGroup.MarginLayoutParams params =
(ViewGroup.MarginLayoutParams) llCropOverlay.getLayoutParams();
float eventX = params.width;
float eventY = 0;
float[] eventXY = new float[]{eventX, eventY};
Matrix invertMatrix = new Matrix();
imageView.getImageMatrix().invert(invertMatrix);
invertMatrix.mapPoints(eventXY);
int x = Integer.valueOf((int) eventXY[0]);
int y = Integer.valueOf((int) eventXY[1]);
int height = params.height;
while (height * 3 > originalBitmap.getHeight()) {
height = height - 10;
}
croppedBitmapByWidth = Bitmap.createBitmap(originalBitmap, (int) orgX, 0,
x, height);
imageView.setImageBitmap(croppedBitmapByWidth);
crop from bottom:
float eventX2 = 0;
float eventY2 = params.height;
float[] eventXY2 = new float[]{eventX2, eventY2};
Matrix invertMatrix2 = new Matrix();
imageView.getImageMatrix().invert(invertMatrix2);
invertMatrix2.mapPoints(eventXY2);
int x2 = Integer.valueOf((int) eventXY2[0]);
int y2 = Integer.valueOf((int) eventXY2[1]);
croppedBitmapByHeight = Bitmap.createBitmap(croppedBitmapByWidth, 0, 0,
croppedBitmapByWidth.getWidth(), y2);
imageView.setImageBitmap(croppedBitmapByHeight);
These is the result that I am after:
Basically I want to scale the 3 images so that they have the same height and all together fill the screen width. The original images will all have same height.
Can this be done using layout, without width calculations from code?
Just use Layout Weights.
In the main layout, or the layout which contains the ImageViews, put
android:weightSum="10"
and then in the individual ImageViews, put layout_weights as shown below, or upto your requirements.
This basically means the width of the images will be 25%, 55% and 20% respectively.
You can use a linear layout with weight attribute specified as shown below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="0dp"
android:src="#drawable/bg_canvas"
android:layout_height="300dp"
android:layout_weight="0.33"/>
<ImageView
android:layout_width="0dp"
android:src="#drawable/bg_canvas"
android:layout_height="300dp"
android:layout_weight="0.33"/>
<ImageView
android:layout_width="0dp"
android:layout_height="300dp"
android:src="#drawable/bg_canvas"
android:layout_weight="0.33"/>
</LinearLayout>
Comment below if you need any further info
try this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
.../>
<ImageView
android:id="#+id/imageView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
.../>
<ImageView
android:id="#+id/imageView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
.../>
</LinearLayout>
the "magic" is in the weight component. you define a total weight of 3 in the layout and your image views should take a third of it, so the value is 1.
For my case the images needed to be updated at runtime, so none of the answers were exact fit.
I ended up extending LinearLayout and writing a small routine that unifies all images heights and make sure that all images together fill the LinearLayout width. In case someone is trying to achieve the same, my code looks like this:
public class MyImgLayout extends LinearLayout
{
public MyImgLayout(Context context)
{
super(context);
}
public void setup(ArrayList<String> images)
{
this.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
this.setLayoutParams(layoutParams); //set 0 height until we calculate it in onMeasure
for (String image : images) {
ImageView ivArticle = new ImageView(getContext());
setImageFromName(image, ivArticle); //this where you set the image
this.addView(ivArticle);
}
}
private void scaleImages()
{
if(getMeasuredHeight() == 0 && getMeasuredWidth() > 0) {
if (isHorizontal) {
double childRatioSum = 0;
int images = 0;
for (int i = 0; i < getChildCount(); i++) {
ImageView iv = (ImageView) getChildAt(i);
double width = iv.getDrawable().getIntrinsicWidth();
double height = iv.getDrawable().getIntrinsicHeight();
if (height > 0) {
childRatioSum += width / height;
images++;
}
}
if (childRatioSum > 0 && images == getChildCount()) {
//all images are downloaded, calculate the container height
//(add a few pixels to makes sure we fill the whole width)
double containerHeight = (int) (getMeasuredWidth() / childRatioSum) + images * 0.5;
for (int i = 0; i < getChildCount(); i++) {
ImageView iv = (ImageView) getChildAt(i);
double width = iv.getDrawable().getIntrinsicWidth();
double height = iv.getDrawable().getIntrinsicHeight();
iv.setLayoutParams(new LinearLayout.LayoutParams((int) (width * (containerHeight / height)), (int) containerHeight));
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) this.getLayoutParams();
params.width = LayoutParams.MATCH_PARENT;
params.height = (int) containerHeight;
this.setLayoutParams(params);
requestLayout();
}
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
scaleImages();
}
}
Good evening! I'm trying to setPadding on a custom View i built and the native setPadding() did nothing so i wrote my own... After a while i realized that setPadding gets called several times after my original call and i have no idea why... Please help :) (I realize that my custom setPadding maybe quite excessive ^^)
Here is the XML containing the View. It's the PieChart.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/PieDialog_llParent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/PieDialog_tvHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Header"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/PieDialog_tvDiv1"
android:layout_width="match_parent"
android:layout_height="2dp"
android:textSize="0sp"/>
<TextView
android:id="#+id/PieDialog_tvDiv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="0sp" />
<com.SverkerSbrg.Spendo.Statistics.Piechart.PieChart
android:id="#+id/PieDialog_Pie"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/PieDialog_tvDiv3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="0sp" />
<FrameLayout
android:id="#+id/PieDialog_flClose"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/PieDialog_tvClose"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Large Text" />
</FrameLayout>
</LinearLayout>
And here is the code where i use the xml:
package com.SverkerSbrg.Spendo.Transaction.TransactionList.PieDialog;
imports...
public class PieDialog extends SpendoDialog{
private TransactionSet transactionSet;
private TransactionGroup transactionGroup;
private GUI_attrs gui_attrs;
private PieData pieData;
private PieChart pie;
private TextView tvHeader;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.transaction_list_pie_dialog, null);
LinearLayout llParent = (LinearLayout) view.findViewById(R.id.PieDialog_llParent);
llParent.setBackgroundColor(gui_attrs.color_Z0);
tvHeader = (TextView) view.findViewById(R.id.PieDialog_tvHeader);
tvHeader.setTextSize(gui_attrs.textSize_header);
TextView tvDiv1 = (TextView) view.findViewById(R.id.PieDialog_tvDiv1);
tvDiv1.setBackgroundColor(gui_attrs.color_Z2);
TextView tvDiv2 = (TextView) view.findViewById(R.id.PieDialog_tvDiv2);
tvDiv2.setPadding(0, gui_attrs.padding_Z0, 0, 0);
PieChart pie = (PieChart) view.findViewById(R.id.PieDialog_Pie);
pie.setPadding(40, 10, 40, 10);
builder.setView(view);
AlertDialog ad = builder.create();
return ad;
}
public void initialize(GUI_attrs gui_attrs, TransactionSet transactionSet, long groupIdentifier){
this.gui_attrs = gui_attrs;
this.transactionSet = transactionSet;
}
}
Just to extrapolate on my comment, it is your custom View object's responsibility to respect the padding that is set. You can do something like the following to make sure that you handle that case:
onMeasure()
int desiredWidth, desiredHeight;
desiredWidth = //Determine how much width you need
desiredWidth += getPaddingLeft() + getPaddingRight();
desiredHeight = //Determine how much height you need
desiredHeight += getPaddingTop() + getPaddingBottom();
int measuredHeight, measuredWidth;
//Check against the MeasureSpec -- if it's MeasureSpec.EXACTLY, or MeasureSpec.AT_MOST
//follow those restrictions to determine the measured dimension
setMeasuredDimension(measuredWidth, measuredHeight);
onLayout()
int leftOffset = getPaddingLeft();
int topOffset = getPaddingTop();
//layout your children (if any) according to the left and top offsets,
//rather than just 0, 0
onDraw()
canvas.translate (getPaddingLeft(), getPaddingTop());
//Now draw your stuff as normal
I'm currently working on an app that has a RelativeLayout that has 4 child FrameLayouts, each FrameLayout has a set of ImageViews inside it and the inside View has it's own behavior. I'm trying to implement a drag and drop to theFrameLayouts while implementing the onTouchListener I found in this tutorial. but unfortunately the drag 'n drop doesn't work properly and nothing is happening.
any thoughts on how to implement the drag and drop correctly? what am I missing?
here is the xml code for a single child of the FrameLayouts:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="80dp"
android:layout_height="108dp" >
<ImageView
android:id="#+id/secondImage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/back" />
<ImageView
android:id="#+id/firstImage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/c2" />
</FrameLayout>
here is the xml code for the main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/pinecropped"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/cardNumber1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="60dp" >
<include layout="#layout/card" />
</FrameLayout>
<FrameLayout
android:id="#+id/cardNumber2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/cardNumber1"
android:layout_marginLeft="50dp"
android:layout_marginTop="100dp" >
<include layout="#layout/card" />
</FrameLayout>
<FrameLayout
android:id="#+id/cardNumber3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp" >
<include layout="#layout/card" />
</FrameLayout>
<FrameLayout
android:id="#+id/cardNumber4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/cardNumber3"
android:layout_marginRight="50dp"
android:layout_marginTop="100dp" >
<include layout="#layout/card" />
</FrameLayout>
</RelativeLayout>
here is the Java code for the single child:
public class Card implements OnClickListener {
private int _resId;
private Context _context;
private ImageView firstImage, secondImage;
private boolean isFirst;
public Card(Context context, FrameLayout parent) {
_context = context;
firstImage = (ImageView) parent.findViewById(R.id.firstImage);
secondImage = (ImageView) parent.findViewById(R.id.secondImage);
}
public void setupCards(int resId, boolean hasBackSide) {
_resId = resId;
Bitmap temp = BitmapFactory.decodeResource(_context.getResources(),
_resId);
firstImage.setImageBitmap(temp);
if (hasBackSide) {
temp = BitmapFactory.decodeResource(_context.getResources(),
R.drawable.back);
}
secondImage.setImageBitmap(temp);
isFirst = true;
secondImage.setVisibility(View.GONE);
}
// MORE IMPLEMENTATION
}
this is my main activity Java code:
public class FaceUpActivity extends Activity {
FrameLayout firstCard, secondCard, thirdCard, forthCard;
Card cardNumber1, cardNumber2, cardNumber3, cardNumber4;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initUI();
}
private void initUI() {
firstCard = (FrameLayout) findViewById(R.id.cardNumber1);
secondCard = (FrameLayout) findViewById(R.id.cardNumber2);
thirdCard = (FrameLayout) findViewById(R.id.cardNumber3);
forthCard = (FrameLayout) findViewById(R.id.cardNumber4);
cardNumber1 = new Card(this, firstCard);
cardNumber2 = new Card(this, secondCard);
cardNumber3 = new Card(this, thirdCard);
cardNumber4 = new Card(this, forthCard);
cardNumber1.setupCards(R.drawable.c2, true);
cardNumber2.setupCards(R.drawable.d0, true);
cardNumber3.setupCards(R.drawable.h5, true);
cardNumber4.setupCards(R.drawable.sj, true);
firstCard.setOnTouchListener(dragMe);
secondCard.setOnTouchListener(dragMe);
thirdCard.setOnTouchListener(dragMe);
forthCard.setOnTouchListener(dragMe);
}
OnTouchListener dragMe = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
FrameLayout.LayoutParams params = (LayoutParams) v
.getLayoutParams();
int maxWidth = getWindowManager().getDefaultDisplay().getWidth();
int maxHeight = getWindowManager().getDefaultDisplay().getHeight();
int topMargin, leftMargin;
int cond = v.getId();
if (cond == R.id.cardNumber1 || cond == R.id.cardNumber2
|| cond == R.id.cardNumber3 || cond == R.id.cardNumber4) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
topMargin = (int) event.getRawY() - (v.getHeight());
leftMargin = (int) event.getRawX() - (v.getWidth()) / 2;
if (topMargin < 0) {
params.topMargin = 0;
} else if (topMargin > maxHeight) {
params.topMargin = maxHeight - v.getHeight();
} else {
params.topMargin = topMargin;
}
if (leftMargin < 0) {
params.leftMargin = 0;
} else if (leftMargin > maxWidth) {
params.leftMargin = maxWidth - (v.getWidth() / 2);
} else {
params.leftMargin = leftMargin;
}
v.setLayoutParams(params);
break;
case MotionEvent.ACTION_MOVE:
topMargin = (int) event.getRawY() - (v.getHeight());
leftMargin = (int) event.getRawX() - (v.getWidth()) / 2;
if (topMargin < 0) {
params.topMargin = 0;
} else if (topMargin > maxHeight) {
params.topMargin = maxHeight - v.getHeight();
} else {
params.topMargin = topMargin;
}
if (leftMargin < 0) {
params.leftMargin = 0;
} else if (leftMargin > maxWidth) {
params.leftMargin = maxWidth - (v.getWidth() / 2);
} else {
params.leftMargin = leftMargin;
}
v.setLayoutParams(params);
break;
}
}
return true;
}
};
}
Why your D&D is not working:
D&D is not working because your Card (that useses the internal FrameLayout) is implementing the onClick event that "eat" the d&d event.
Solutions are two:
you can have 2 different areas, one for the click event (the biggest part of the card), one for the d&d event (the bottom-left edge of the card). You can see a live example in the Android Music player that implements this solution.
Otherwise you can handle the two events at the same time:
click == down+up in the same time (under 100ms) in the same x/y location
dd == down+up in different times ( > 50/100ms)
I think there are a couple of potential problems:
Are you sure you're getting the correct IDs in your onTouch()? (since the touch listener is only used with your card views, you propably can remove the if checking for the IDs)
You are using a FrameLayout - so use the x and y position instead of margins edit: my bad, you're using RelativeLayout, so the margins are kind of right. Though, I'd use a FrameLayout instead
the API says you need to return true in onTouch() if you consumed the event, false otherwise (you're returning true when you didn't move the cards and nothing when you did)
I am trying to add views to LinearLayout dynamically as much as it possible (depending on screen width).
I do this before the LinearLayout displays on screen.
My LinearLayout:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="#666"/>
My view to display in LinearLayout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#999">
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:src="#drawable/no_photo"/>
</FrameLayout>
I add views to layout:
int allItems = 50;
int currentItem = 0;
while(currentItem < allItems)
{
FrameLayout view = (FrameLayout) inflater.inflate(R.layout.fl, null);
linearLayout.addView(view);
if (linearLayout.getMeasuredWidth() >= this.getWidth())
{
linearLayout.removeView(view);
break;
}
}
but linearLayout.getMeasuredWidth() and this.getWidth() is 0;
I know, that i must use View.measure method to calculate view size before it became visible, but i don't know where and how it use.
Edit your code as below :
Display display = getWindowManager().getDefaultDisplay();
int maxWidth = display.getWidth();
int widthSoFar=0;
int allItems = 50;
int currentItem = 0;
while(currentItem < allItems) {
FrameLayout view = (FrameLayout) inflater.inflate(R.layout.fl, null);
linearLayout.addView(view);
view .measure(0, 0);
widthSoFar = widthSoFar + view.getMeasuredWidth();
if (widthSoFar >= maxWidth) {
linearLayout.removeView(view);
break;
}
}
Hope this helps you