ChatKit library : incoming image wrong margins - android

I'm using ChatKit library (https://github.com/stfalcon-studio/ChatKit/) for a chat feature in my app.
In the message list provided by the library, I also included images messages.
It works fine, but the bubble's layout of the images is ambiguous, as the following picture :
Bubble picture 1 and 3 should be aligned on the right side, but they are stick on the left in the available space for incoming messages.
Note that the default text messages bubbles are displayed correctly on
the right.
I didn't find any attributes for the layout in the library to configure this behaviour.
This is my XML for the message list :
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_comments"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.stfalcon.chatkit.messages.MessagesList
android:id="#+id/messagesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/input_comment"
app:incomingDefaultBubbleColor="#color/lightGrayRetail"
app:incomingTimeTextColor="#color/white"
app:incomingDefaultBubblePressedColor="#color/lightGrayRetail"
app:incomingDefaultImageOverlayPressedColor="#color/lightGrayRetail"
app:outcomingDefaultBubblePressedColor="#color/pinkRetail"
app:outcomingDefaultImageOverlayPressedColor="#color/pinkRetail"
app:outcomingDefaultBubbleColor="#color/pinkRetail"
app:outcomingTimeTextColor="#color/colorMaterialGray" />
</android.support.v4.widget.SwipeRefreshLayout>
My incoming text message layout layout :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="8dp">
<TextView
android:id="#+id/displayNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/bubble"
android:layout_marginStart="8dp"
android:layout_marginBottom="8dp"
android:textColor="#color/colorMaterialGray"/>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#id/messageUserAvatar"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginEnd="8dp"
android:src="#drawable/woman" />
<ImageView
android:id="#+id/onlineIndicator"
android:layout_width="12dp"
android:layout_height="12dp"
android:layout_alignEnd="#id/messageUserAvatar"
android:layout_alignTop="#id/messageUserAvatar"
android:layout_marginEnd="5dp" />
<LinearLayout
android:id="#id/bubble"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:layout_below="#+id/displayNameTextView"
android:layout_toEndOf="#id/messageUserAvatar"
android:orientation="vertical">
<TextView
android:id="#id/messageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="4dp"
android:layout_marginStart="8dp"/>
</LinearLayout>
<TextView
android:id="#+id/incomingTimeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#id/bubble"
android:layout_below="#id/bubble"
android:layout_marginEnd="4dp"
android:text="18:00"
android:layout_marginTop="4dp"
android:textColor="#color/colorMaterialGray" />
</RelativeLayout>
Outcoming layout :
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="8dp">
<LinearLayout
android:id="#id/bubble"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginStart="40dp"
android:orientation="vertical">
<TextView
android:id="#id/messageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<TextView
android:id="#+id/outcomingTimeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#id/bubble"
android:layout_below="#id/bubble"
android:textColor="#color/colorMaterialGray"
android:layout_marginStart="16dp"/>
</RelativeLayout>
MessageHolder of outcoming :
public class CustomOutcomingMessageViewHolder extends MessageHolders.OutcomingTextMessageViewHolder<Comment> {
private TextView mOutcomingTimeTextView;
public CustomOutcomingMessageViewHolder(View itemView) {
super(itemView);
mOutcomingTimeTextView = itemView.findViewById(R.id.outcomingTimeTextView);
}
#Override
public void onBind(Comment comment) {
super.onBind(comment);
if(comment.getmContent() != null){
if(comment.getmContent().length() > 3){
SimpleDateFormat timeOutput = new SimpleDateFormat("HH:mm", Locale.FRANCE);
String commentPostedTime = timeOutput.format(comment.getmPostedDate());
mOutcomingTimeTextView.setText(commentPostedTime);
}
}
}
}
Any ideas ?

This happened to me without using any MessageHolder, I could fix it by assigning the same width to all images:
int width = Math.round( (float) getScreenWidthHeight().x * 0.8f); // width = 80% of screen's max width
int height = Math.round((float) bitmap.getHeight() / ((float) bitmap.getWidth() / (float) width));
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap), width, height, true);
where getScreenWidthHeight() is:
private Point getScreenWidthHeight(Activity activity) {
Display display = activity.getWindowManager(). getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size;
}

Did you check the sender ids in your code to be different for sender and receiver side by the id which is gotten from getId of message model? According to the library you need to determine the senderId in the Adapter initialization:
MessagesListAdapter<Message> adapter = new MessagesListAdapter<>(senderId,
imageLoader);
messagesList.setAdapter(adapter);
Library decides whether to align left or right according to senderIds comparison.

For anyone using the default MessagesListAdapter and ViewHolders, outgoing picture message ImageViews don't have their alignment set, but their parent view width is set to match_parent, which is why the image isn't aligned correctly.
item_outcoming_image_message.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="8dp">
<com.stfalcon.chatkit.utils.RoundedImageView
android:id="#id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_marginLeft="#dimen/message_outcoming_bubble_margin_left"
android:layout_marginStart="#dimen/message_outcoming_bubble_margin_left" />
So, after looking through some of the library code, I found one solution is to simply override onBindViewHolder():
messagesAdapter = new MessagesListAdapter<Message>(senderId, imageLoader) {
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
super.onBindViewHolder(holder, position);
if (holder.getItemViewType() == -132) { // -132 is an outgoing picture message
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.itemView.findViewById(com.stfalcon.chatkit.R.id.image).getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_END);
}
}
};

Fixed it by setting a fixed width using ConstraintLayout
val holdersConfig = MessageHolders()
.setIncomingTextConfig(
CustomIncomingTextMessageViewHolder::class.java,
R.layout.item_custom_incoming_text_message
)
Here is my item_custom_outcoming_image_message
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/imageMessageContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp"
tools:context=".chatting.ChattingFragment">
<com.stfalcon.chatkit.utils.RoundedImageView
android:id="#id/image"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="#drawable/ic_chat_pick_image"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent=".8"
tools:srcCompat="#tools:sample/backgrounds/scenic" />
<View
android:id="#id/imageOverlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="#id/image"
app:layout_constraintEnd_toEndOf="#id/image"
app:layout_constraintStart_toStartOf="#id/image"
app:layout_constraintTop_toTopOf="#id/image"
tools:visibility="gone" />
<ImageView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/image"
tools:src="#drawable/ic_message_status_processing" />
<TextView
android:id="#id/messageTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="#id/status"
app:layout_constraintEnd_toStartOf="#+id/status"
app:layout_constraintTop_toTopOf="#id/status"
tools:text="12:15" />
</androidx.constraintlayout.widget.ConstraintLayout>

Related

Can't change GridView dynamically

I'm developing an app. In this app there's an alertdialog that opens when you click a point.
In this alert dialog there are two edittext, a gridview and a button. The gridview has associated a BaseAdapter that convert Uris to IconView (a class that extends ImageView) using Glide.
I want to set a maximum height of 350dp, but if there is just one row (there'll be always one image) I want the gridview to adapt.
I tried this way: How to have a GridView that adapts its height when items are added
But it doesn't work. So what I've tried is to count the number of elements and if there's is more than 2, set 350dp of height if there is less than 2, set 175dp. But it doesnt work.
The alert dialog layout:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/puntoName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:fontFamily="sans-serif"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/puntoDescripcion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:maxHeight="100dp"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/puntoName" />
<GridView
android:id="#+id/photo_grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:gravity="center"
android:horizontalSpacing="6dp"
android:numColumns="2"
android:verticalSpacing="5dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/puntoDescripcion"></GridView>
<Button
android:id="#+id/cerrar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cerrar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/photo_grid" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is the code I'm using in order to change GridView height:
fun checkSize() {
val popUp: View = fragmentCaller.layoutInflater.inflate(R.layout.popup,null)
var photogrid: GridView = popUp.findViewById(R.id.photo_grid)
var params: ViewGroup.LayoutParams = photogrid.layoutParams
var tam: Int = 175
if (adapter.getDataSource().size>2) {
tam = DpToPixels(350)
}
photogrid.layoutParams.height = tam
photogrid.requestLayout()
}
private fun DpToPixels(dp: Int) : Int {
val escala: Float = fragmentCaller.requireContext().resources.displayMetrics.density;
var tam: Int = (dp * escala + 0.5f).toInt()
return tam
}
The size of the gridView is always 0. I don't know why. I just want to set android:layout_height programmatically. I call checkSize() method after I call Dialog.show() and everytime I do changes in the elements of adapter.
Thanks.

Add view to constraintLayout with constraints similar to another child

I have a constraint layout (alpha9) with views spread all over it, and I have one particular ImageView that I need to replicate and add more of like it.
The layout is like so :
The main purpose is to animate 5 of those "coin" imageViews when the button is pressed. The imageViews i need to generated sha'll have exact properties of the the imageView behind the Button down below (with same constraints)
What i tried to do is the following :
private ImageView generateCoin() {
ImageView coin = new ImageView(this);
constraintLayout.addView(coin,-1,originCoinImage.getLayoutParams());//originCoinImage is the imageView behind the button
coin.setImageResource(R.drawable.ic_coin);
coin.setScaleType(ImageView.ScaleType.FIT_XY);
coin.setVisibility(View.VISIBLE);
return coin;
}
And it failed. EDIT: It failed to show what i wanted , sometimes it shows a coin in the top left of the screen , sometimes it doesn't show anything but either way , the number of coins increments (meaning the animation is trying to actually do something and then calling the onAnimationFinished method)
I used for animation the library EasyAndroidAnimations
the code is as follows :
MainActivity.java
#OnClick(R.id.addCoin)
public void addCoin() {
// for (int x = 0 ; x < 5 ; x++){
final View newCoin = generateCoin();
sendCoin(newCoin, 300, new AnimationListener() {
#Override
public void onAnimationEnd(com.easyandroidanimations.library.Animation animation) {
incrementCoins();
constraintLayout.removeView(newCoin);
shakeCoin(targetCoinImage, 200, null);
}
});
// }
}
private void incrementCoins() {
coins++;
coinNumber.setText(String.valueOf(coins));
}
private void sendCoin(View coinView, long duration, AnimationListener listener) {
new TransferAnimation(coinView)
.setDestinationView(targetCoinImage)
.setDuration(duration)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setListener(listener)
.animate();
}
private void shakeCoin(View coinView, long duration, AnimationListener listener) {
new ShakeAnimation(coinView)
.setDuration(duration)
.setShakeDistance(6f)
.setNumOfShakes(5)
.setListener(listener)
.animate();
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="seaskyways.canvasanddrawtest.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Coins : "
android:textSize="30sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/coinNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="16dp"
android:layout_marginStart="8dp"
android:text="0"
android:textColor="#color/colorPrimary"
android:textSize="50sp"
android:textStyle="normal|bold"
app:layout_constraintBottom_toBottomOf="#+id/textView"
app:layout_constraintLeft_toRightOf="#+id/textView"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="#+id/textView" />
<ImageView
android:id="#+id/coinOrigin"
android:layout_width="50dp"
android:layout_height="50dp"
android:scaleType="fitXY"
app:layout_constraintBottom_toBottomOf="#+id/addCoin"
app:layout_constraintLeft_toLeftOf="#+id/addCoin"
app:layout_constraintTop_toTopOf="#+id/addCoin"
app:srcCompat="#drawable/ic_coin"
app:layout_constraintRight_toRightOf="#+id/addCoin" />
<ImageView
android:id="#+id/coinTarget"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:scaleType="fitXY"
app:layout_constraintBottom_toBottomOf="#+id/coinNumber"
app:layout_constraintLeft_toRightOf="#+id/coinNumber"
app:layout_constraintTop_toTopOf="#+id/coinNumber"
app:srcCompat="#drawable/ic_coin" />
<Button
android:id="#+id/addCoin"
android:layout_width="0dp"
android:layout_height="75dp"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
android:text="Button"
android:textAlignment="center"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
ConstraintLayout.LayoutParams cache its parameters, and is associated to the widget you use it on, so you cannot simply pass one widget's layoutParams to another.
You have to instead generate a new layoutParams for your new object, and copy the corresponding fields.
For example, if you have something like:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_marginTop="16dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="16dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="16dp" />
</android.support.constraint.ConstraintLayout>
Then you could do:
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.content_main);
ConstraintLayout.LayoutParams params =
(ConstraintLayout.LayoutParams) button.getLayoutParams();
Button anotherButton = new Button(this);
ConstraintLayout.LayoutParams newParams = new ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.WRAP_CONTENT,
ConstraintLayout.LayoutParams.WRAP_CONTENT);
newParams.leftToLeft = params.leftToLeft;
newParams.topToTop = params.topToTop;
newParams.leftMargin = params.leftMargin;
newParams.topMargin = params.topMargin;
layout.addView(anotherButton, -1, newParams);
This would put the second button exactly in the same place as the one defined in XML.

Making Recyclerview Fixed Height and Scrollable

SOLVED CHECK ANSWER BELOW...
So I am trying to create a comments functionality for my Android app and I want to display the comments inside a recyclerview and then have a button and textview below the recyclerview to add comments. I want to have the recyclerview a certain height and make it scrollable if there are lots of comments because I dont want the users to have to scroll down the screen to find the add button.
I couldn't get it to work so I was wondering if anyone else had that issue.
I have all the adapter and everything set up, I am just having trouble with the recyclerview.
Thanks.
I prob was not clear on what I was trying to accomplish. I am trying to create a cardview where it will display all the comments and the ability to add a new comment. The recyclerview will take up approx 80% of the height and then the last 20% is for the edittext and button.
My XML (Scroll to last cardview where the recyclerview is)
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollview">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ProfilePageActivity"
>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/profilepagetoolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:minHeight="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:layout_marginTop="35dp"
android:layout_below="#+id/profilepagetoolbar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:id="#+id/aboutCard">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="300dp"
android:gravity="center_vertical"
android:orientation="vertical"
android:layout_alignTop="#+id/aboutCard"
android:focusable="true"
android:focusableInTouchMode="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="-60dp"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="#color/text"
android:textSize="20sp"
android:text="ABOUT" />
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#color/dividers" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="10dp">
<ImageView
android:id="#+id/nameicon"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_margin="8dp"
android:transitionName="appIcon"
android:background="#drawable/ic_account_circle_black_24dp"/>
<TextView
android:id="#+id/Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="8dp"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="#color/secondary"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="10dp">
<ImageView
android:id="#+id/locationicon"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_margin="8dp"
android:transitionName="appIcon"
android:background="#drawable/ic_map_black_24dp"/>
<TextView
android:id="#+id/Location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="11dp"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="#color/secondary"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="10dp">
<ImageView
android:id="#+id/websiteIcon"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_margin="8dp"
android:transitionName="appIcon"
android:background="#drawable/ic_explore_black_24dp"/>
<TextView
android:id="#+id/Website"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="11dp"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="#color/secondary"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:layout_marginTop="35dp"
android:layout_below="#+id/aboutCard"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:id="#+id/writeComment"
android:layout_alignParentTop="false"
android:layout_alignParentBottom="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="300dp"
android:gravity="center_vertical"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="-100dp"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="#color/text"
android:textSize="20sp"
android:text="Comments" />
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#color/dividers"
android:id="#+id/divider"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:layout_width="244dp"
android:layout_height="wrap_content"
android:id="#+id/editComment"
android:layout_below="#+id/divider"
android:textColor="#color/text"
android:hint="Write a comment..."/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create"
android:id="#+id/btnComment"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:layout_marginTop="20dp"
android:layout_below="#+id/writeComment"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:id="#+id/commentsCard">
<LinearLayout
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="0dp"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="#color/text"
android:textSize="20sp"
android:text="Comments" />
<android.support.v7.widget.RecyclerView
android:id="#+id/commentsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true" />
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
</ScrollView>
The second and first comment are being cut off.
So what my problem was that for some reason, Recyclerview didnt wrap_contents. I did some research (thanks stackoverflow) and found out a lot of people were having this issue and they posted solutions for this issue.
Basically, I had to use a customized linearlayoutmanger to fix the issue.
I will post the solution they posted and links to their questions. thanks for whoever tried to help, I appreciate it.
This is the extra file I needed. And then I had to set my recyclerview to use this layout instead of the default one.
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
#Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
}
After that. Change this:
mProductsRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
To this:
mRecyclerView.setLayoutManager(new MyLinearLayoutManager(getApplicationContext(),1,false));
Three new paramets(Context, int Orientation, boolean reverse);
basically, i put 1 for orientation so it shows vertiacally, and false for revers so it shows up how it is ordered in my List.
Links to other people's question with same problem as me.
Nested Recycler view height doesn't wrap its content
Nested Recycler view height doesn't wrap its content
Thanks once again guys. Hope this helps someone else
Add this code in your activity, will set the height of your recycler view to the 90% of user's screen window.
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int a = (displaymetrics.heightPixels*90)/100;
recylcerView.getLayoutParams().height =a;
and your comment layout below the your recyclerView
like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/mudit"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="5dp"
android:scrollbars="vertical" />
</LinearLayout>
<RelativeLayout
android:layout_below="#+id/mudit"
android:id="#+id/rl_commentWrap"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:ems="10" />
<Button
android:id="#+id/plusButton"
style="android:buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Send"
android:textColor="#FFFFFF"
android:translationZ="5dp" />
</RelativeLayout>
</RelativeLayout>
In my situation I had a DialogFragment, in which there are 2 recyclers and 2 horizontal linear layouts with 2 buttons.
Dialog from top to bottom looks like this:
RecyclerView A
Horizontal linear layout X with 2 buttons
RecyclerView B
Horizontal linear layout Y with 2 buttons
On top of that both recyclers size is dynamic.
Recycler A size can change based on user swipes in both recyclers.
Recycler B size can change based on its item click listener.
What I wanted to achieve was to cut the Dialog from top to bottom
and have each of those four views its constant part of the Dialog height.
What worked was to divide it first to 2 separate relative layouts, say lTOP and lBottom. Set lTOP alignParentTop, lBottom alignParentBottom and layout_below lTOP.
Both of them width match_parent, height wrap_content.
Then in each of them create 1 relative (say lINTop) and 1 linear (say lINBottom) layouts. lINTop has recycler, lINBottom has 2 buttons.
Set both lINTop lINBottom width match_parent, height wrap_content.
Set lINTop alignParentTop, lINBottom alignParentBottom and below lINTop.
Set lINTop orientation vertical, lINBottom orientation horizontal.
Set recyclers width match_parent, height wrap_content.
Then i putted this all inside single relative layout with width/height wrap_content and orientation vertical.
Then this inside scrollview with width/height match_parent and orientation vertical.
Then needed a little code magic for setting up recycler in onCreateView:
For Recycler A:
private void setupRecyclerA() {
// use a linear layout manager
RecyclerView.LayoutManager layManUS = new LinearLayoutManager(setupActivity().get());
recyclerA.setLayoutManager(layManUS);
recyclerA.addItemDecoration(new DividerItemDecoration(
setupActivity().get(), LinearLayoutManager.VERTICAL));
recyclerA.setNestedScrollingEnabled(true);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerA.setHasFixedSize(true);
}
For Recycler B:
private void setupRecyclerB() {
// use a linear layout manager
RecyclerView.LayoutManager layManUS = new LinearLayoutManager(setupActivity().get());
recyclerB.setLayoutManager(layManUS);
recyclerB.addItemDecoration(new DividerItemDecoration(
setupActivity().get(), LinearLayoutManager.VERTICAL));
recyclerB.setNestedScrollingEnabled(true);
// set fixed height
DisplayMetrics displaymetrics = new DisplayMetrics();
setupActivity().get().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
// set height to 30 percent of dialog
int a = (displaymetrics.heightPixels*30)/100;
recyclerB.getLayoutParams().height =a;
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerB.setHasFixedSize(true);
}
I didnt invented it, I just combined solutions from many different Stack Overflow questions which I dont even remember now, sorry and thanks to the Creators.
I had a similar problem and solved it with RelativeLayout. I have this layout:
I wanted the top and bottom cardview to stay in place while scrolling the central recyclerView. Tried with LinearLayout and ConstraintLayout but didn't work, the bottom CardView only was shown when I scrolled to the end of the recycler.
This is my code, notice the layout_above, layout_below, and layout_alignParentBottom attributes:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grisMasOscuro">
<androidx.cardview.widget.CardView
android:id="#+id/cv1"
android:layout_width="match_parent"
android:layout_height="50dp" >
<!-- cardview content -->
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/cv3"
android:layout_below="#id/cv1">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/myRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:id="#+id/cv3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true">
<!-- cardview content -->
</androidx.cardview.widget.CardView>
</RelativeLayout>
I found another solution.
If you will wrap recyclerview in RelativeLayout, it will solve the problem easily.
Thanks.

2 TextViews, left with ellipsis, right with nowrap, single line

It's the first time I post on this forum, hope it's gonna be fine :)
I'm developping an Android App for public transportation in my city.
Here is what I have
[ |short destination ||next departure| ]
[ |way too long dest...||next departure| ]
Here is what I want:
[ |short destination||next departure| ]
[ |way too long dest...||next departure| ]
Here is a more complete example: s28.postimg.org/5gejnvfd9/actual2.png
Weird coloured backgrounds are just here to easily identify layouts/textviews. You can also ignore the brown line (which is ok).
Basically, I want to have the destination [red background] which have a variable length, and on its right, I want the first departure time [green background]. Everything on one line.
I need to always have the first departure information fully displayed (nowrap). The destination could be wrapped with an ellipsis (...).
[Optional question, how to replace the ellipsis '...' with '.' ?]
Here is the best working code I have so far:
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txtTitleDestination"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/txtTitleFirstDeparture"
android:background="#FF0000"
android:ellipsize="end"
android:maxLines="1"
android:padding="0dp"
android:scrollHorizontally="true"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtTitleFirstDeparture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_alignParentRight="true"
android:background="#00FF00"
android:ellipsize="none"
android:maxLines="1"
android:padding="0dp"
android:textSize="18sp"
android:textStyle="bold"
/>
</RelativeLayout>
I've tried TableLayout and LinearLayour instead of the RelativeLayout, but with no success :(
Any idea how I could do that?
Thanks in advance!
Louloox
[SOLVED]
Just have to lightly modify the valbertos answer:
titleDestination.post(new Runnable() {
#Override
public void run() {
int widthTextViewDeparture = measureTextWidthTextView(titleFirstTime, pContext);
int widthTextViewDestination = titleDestination.getWidth();
int widthTextViewParent = rl_parent.getWidth();
if(widthTextViewDestination + widthTextViewDeparture > widthTextViewParent) {
titleDestination.setWidth(widthTextViewParent - widthTextViewDeparture);
titleDestination.setEllipsize(TruncateAt.END);
titleDestination.setHorizontallyScrolling(true);
}
}
});
Setting the Ellipsis only if necessary makes the text properly truncated.
Before:
Lingolsheim Thiergaten --> Lingolsheim... [1'23"] 21h23
With the modification:
Lingolsheim Thiergaten --> Lingolsheim Thi... [1'23"] 21h23
Thanks again :)
You don't need do it programmatically, ConstraintLayout is a magic!
Just use this code
app:layout_constraintHorizontal_bias="0" align view left
app:layout_constrainedWidth="true" to wrap left text
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/leftText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
app:layout_constrainedWidth="true"
app:layout_constraintHorizontal_bias="0"
app:layout_constraintEnd_toStartOf="#id/rightText"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="|short destination|" />
<TextView
android:id="#+id/rightText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/leftText"
app:layout_constraintTop_toTopOf="parent"
tools:text="|next departure|" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is result
I found a way to do it using Linear Layout, the trick is not to forget width="wrap_content" for the linearLayout, hope it can help.
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="end"
android:singleLine="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true" />
To do what you are asking for, you must adjust the width of the first view dynamically based on the text width of the second view.
//Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
final TextView tv_1 = (TextView) findViewById(R.id.tv_1);
tv_1.post(new Runnable() {
#Override
public void run() {
View rl_parent = findViewById(R.id.rl_parent);
TextView tv_2 = (TextView) findViewById(R.id.tv_2);
int widthTextView2 = measureTextWidthTextView(tv_2);
if(tv_1.getWidth() + widthTextView2 > rl_parent.getWidth()) {
tv_1.setWidth(tv_1.getWidth() - widthTextView2);
}
}
});
}
private int measureTextWidthTextView(TextView textView) {
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(getScreenWidth(), View.MeasureSpec.AT_MOST);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
textView.measure(widthMeasureSpec, heightMeasureSpec);
return textView.getMeasuredWidth();
}
private int getScreenWidth() {
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.x;
}
//Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/rl_parent"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#348D63">
<TextView
android:id="#+id/tv_1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#BD160B"
android:gravity="center_vertical"
android:maxLines="1"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Elsau Elsau Elsau Elsau Elsau Elsau Elsau"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/tv_1"
android:gravity="center_vertical"
android:minWidth="50dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="[11:30 14:23]"
android:textStyle="bold" />
</RelativeLayout>
<!-- Rest of the layout -->
</LinearLayout>
Use android:maxLines="1" instead of android:singleLine="true" to get rid off the ugly dots -as I did in my example.
Also, I recommend you to use include for the "time" section, instead of repeating the TextViews twice. I’ve just done it like that to keep simple the example.
Maybe you should use a LinearLayout instead of RelativeLayout and use the layout_weight attribute.
<LinearLayout android:orientation="horizontal" ...>
<TextView android:id="#+id/txtTitleDestination" android:layout_width="wrap_content" ... />
<TextView android:id="#+id/txtTitleFirstDeparture" android:layout_width="0dp" android:layout_weight="1" ... />
</LinearLayout>

WRAP_CONTENT not working after dynamically adding views

I'm trying to create a fragment that lays out a series of custom views dynamically. The main content for this layout is a RelativeLayout nested in a LinearLayout (to center it horizontally), nested in a ScrollView.
The RelativeLayout has a few TextViews and a 9 patch ImageView that is meant to scale with the dynamically added custom views. However, the image (achievements_bgImageView below) is ending up as the size of the screen, and is not respecting the size of its parent RelativeLayout even after I've added the appropriate amount of custom views. The image scales fine when I manually set the size of achievements_mainLayout (see the commented out lines below), but does nothing if I try to let that RelativeLayout's wrap_content handle its own sizing.
The ScrollView IS respecting the size of the RelativeLayout, as all the content is present, it's simply the imageView that isn't stretching to match the content at this point.
Any help would be appreciated... My manual calculations don't seem to be good enough to account for different devices, despite the fact I'm accounting for screen density and I'm manually forcing the RelativeLayout to a constant width.
It's worth noting that the measured size of the RelativeLayout is always equal to the height of the screen, regardless of whether or not the sum of its content is greater or less than that height. So, essentially, WRAP_CONTENT is simply not doing what it's supposed to be doing. I have nothing referencing any edge of of the RelativeLayout, so circular dependencies shouldn't be a problem.
fragment_achievements.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<RelativeLayout
android:layout_width="320dp"
android:layout_height="wrap_content"
android:id="#+id/achievements_mainLayout">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/achievements_bgImageView"
android:src="#drawable/bkg_achievements9"
android:adjustViewBounds="true"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_centerHorizontal="true"
android:scaleType="fitXY"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name Field"
android:id="#+id/achievements_nameTextView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="28dp"
android:layout_marginTop="30dp"/>
<ImageView
android:layout_width="52dp"
android:layout_height="52dp"
android:id="#+id/achievements_avatarImageView"
android:layout_below="#+id/achievements_nameTextView"
android:layout_alignLeft="#+id/achievements_nameTextView"
android:src="#drawable/achieve_avatar"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Top Moment:"
android:id="#+id/textView2"
android:layout_alignBottom="#+id/achievements_avatarImageView"
android:layout_toRightOf="#+id/achievements_avatarImageView"
android:layout_marginBottom="16dp"
android:layout_marginLeft="4dp"
android:textSize="12dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Me Overall:"
android:id="#+id/textView3"
android:layout_alignTop="#+id/textView2"
android:layout_alignLeft="#+id/textView2"
android:layout_marginTop="16dp"
android:textSize="12dp"/>
<TextView
android:layout_width="52dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="153"
android:id="#+id/achievements_totalPointsTextView"
android:gravity="center"
android:layout_alignTop="#+id/achievements_avatarImageView"
android:layout_alignRight="#+id/achievements_bgImageView"
android:layout_alignEnd="#+id/achievements_bgImageView"
android:layout_marginRight="31dp"
android:textColor="#f7a033"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Moment"
android:id="#+id/achievements_topMomentTextView"
android:layout_alignTop="#+id/textView2"
android:layout_toRightOf="#+id/textView2"
android:layout_marginLeft="5dp"
android:textSize="12dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="153"
android:id="#+id/achievements_overallTextView"
android:layout_alignTop="#+id/textView3"
android:layout_toRightOf="#+id/textView3"
android:layout_marginLeft="5dp"
android:textSize="12dp"/>
</RelativeLayout>
</LinearLayout>
</ScrollView>
AchievementFragment.java
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = null;
fragmentView = inflater.inflate(R.layout.fragment_achievements, container, false);
ImageView avatarImageView = (ImageView)fragmentView.findViewById(R.id.achievements_avatarImageView);
...
// Basic Achievement List Setup
RelativeLayout mainLayout = (RelativeLayout)fragmentView.findViewById(R.id.achievements_mainLayout);
AchievementRow currentRow = null;
List achievementTypeList = CampaignManager.sharedManager().sortedAchievementTypeList();
int achievementCount = achievementTypeList.size();
for (int i = 0; i < achievementCount; i++) {
AchievementType achievementType = (AchievementType)achievementTypeList.get(i);
// Every third achievement creates a new row.
if ((i % 3) == 0) {
AchievementRow row = (AchievementRow)inflater.inflate(R.layout.widget_achievementrow, null);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (currentRow == null) {
layoutParams.addRule(RelativeLayout.BELOW, avatarImageView.getId());
layoutParams.setMargins(10, 70, 10, 0);
} else {
layoutParams.addRule(RelativeLayout.BELOW, currentRow.getId());
layoutParams.setMargins(10, 10, 10, 0);
}
layoutParams.addRule(RelativeLayout.ALIGN_LEFT, backgroundImageView.getId());
layoutParams.addRule(RelativeLayout.ALIGN_RIGHT, backgroundImageView.getId());
row.setLayoutParams(layoutParams);
row.setId(i+1);
mainLayout.addView(row);
currentRow = row;
}
// Now setup the Button
AchievementButton achievementButton = currentRow.buttonForIndex(i % 3);
achievementButton.achievementType = achievementType;
achievementButton.setOnClickListener(achievementButtonListener);
achievementButton.setVisibility(View.VISIBLE);
CacheManager.sharedManager().fetchAchievementThumbnail(getActivity(), achievementButton, achievementType);
}
// This is the manual scaling of mainLayout
// float scale = getResources().getDisplayMetrics().density;
// float headerHeight = scale * 150.0f;
// float rowHeight = scale * 78.0f;
// ViewGroup.LayoutParams mainLayoutParams = mainLayout.getLayoutParams();
// mainLayoutParams.height = (int)(headerHeight + (Math.ceil(achievementCount / 3.0) * rowHeight));
return fragmentView;
}
Try calling requestLayout on the children.
I recently had a similar problem and was similarly frustrated that things like invalidate and requestLayout seemed to do nothing. What I didn't understand is that requestLayout doesn't propagate down to its children; it propagates up to its parents. To re-measure something that was previously measured, I had to call requestLayout on the View that changed rather than the View I actually wanted to resize.
Android does NOT refresh layout of views with "wrap_content" once it has been displayed.
So if you add a child view, or modify the content dynamically, you're screwed.
I do agree that this is a nightmare and a real flaw in Android UI!
To solve that, I've written a static class that recomputes the sizes and forces the update of the layout for the views with "wrap_content"
The code and instructions to use are available here:
https://github.com/ea167/android-layout-wrap-content-updater
Enjoy!
A simple way to update the size of a View with WRAP_CONTENT is change the visibility to GONE and back to the old visibility.
int visibility = view.getVisibility();
view.setVisibility(View.GONE);
view.setVisibility(visibility);
TESTED ON ANDROID JELLY BEAN IN 2014
MAY NOT WORK ON NEWER ANDROID VERSIONS
Ok, I solved this by manually measuring the RelativeLayout immediately after adding all the views and setting the mainLayoutParams height explicitly. I wish I was smarter and knew why it wasn't automatically doing this correctly in the first place, but oh well.
...
mainLayout.measure(0, 0);
ViewGroup.LayoutParams mainLayoutParams = mainLayout.getLayoutParams();
mainLayoutParams.height = mainLayout.getMeasuredHeight() + 10;
...
I encountered same issue when working with LinearLayout which has wrap_content and one child as TextView match_parent.
To fix this I did this:
Remove the TextView programatically and then add it again.
linearLayout.removeView(textView)
linearLayout.addView(textView)
I know it sounds stupid but it works.
In my case calling invalidate didn't work, only this worked.
Depending on your implementation you need to take care of view index inside its parent
You are getting this problem because you set your layout first and then add its content dynamically.
You are telling the layout to wrap to the content that is not yet their. Try using your layout inflater after you have grabbed your content
You should use NestedScrollView Instead of simple scrollview.
here is my sample Activity Layout code
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:background="#F0ECE6"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabIndicatorHeight="6dp"
android:layout_marginTop="-10dp"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<wsit.rentguru.utility.CustomViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
here is code for custom viewpager
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
}
setup function for viewpager in the activity
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new SampleFragment(), " ");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
here is the sample SampleFragment layout code
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F0ECE6"
android:fillViewport="true"
android:scrollbars="vertical"
android:animateLayoutChanges="true"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F0ECE6"
android:focusableInTouchMode="true"
>
<Spinner
android:id="#+id/product_category"
android:layout_margin="20dp"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#drawable/edittext_rectangle_box"
android:gravity="center|left"
android:textSize="14sp"
android:paddingLeft="10dp"
android:drawableRight="#drawable/ic_down_arrow"
/>
<Spinner
android:id="#+id/product_sub_category"
android:layout_below="#+id/product_category"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center|left"
android:visibility="gone"
android:paddingLeft="10dp"
android:background="#android:color/white"
android:drawableRight="#drawable/ic_down_arrow"
/>
<EditText
android:id="#+id/product_title"
android:layout_below="#+id/product_sub_category"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="15dp"
android:background="#android:color/white"
android:hint="PRODUCT TITLE"
android:singleLine="true"
android:imeOptions="actionDone"
android:layout_width="match_parent"
android:gravity="center|left"
android:padding="10dp"
android:textSize="14sp"
android:textColorHint="#000000"
android:layout_height="40dp" />
<LinearLayout
android:id="#+id/availability_layout"
android:layout_below="#+id/product_title"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/availability"
android:textStyle="bold"
android:paddingBottom="10dp"
android:textSize="14sp"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2">
<Button
android:id="#+id/from"
android:background="#android:color/white"
android:hint="FROM"
android:layout_weight="1"
android:gravity="center|left"
android:padding="10dp"
android:textSize="14sp"
android:textStyle="normal"
android:textColorHint="#000000"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"/>
<Button
android:id="#+id/to"
android:background="#android:color/white"
android:hint="TO"
android:layout_weight="1"
android:gravity="center|left"
android:padding="10dp"
android:textSize="14sp"
android:textColorHint="#000000"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/product_location_layout"
android:layout_below="#+id/availability_layout"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/product_location"
android:textStyle="bold"
android:paddingBottom="10dp"
android:textSize="14sp"
/>
<Spinner
android:id="#+id/state_spinner"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#drawable/edittext_rectangle_box"
android:gravity="center|left"
android:textSize="14sp"
android:layout_marginBottom="10dp"
android:drawableRight="#drawable/ic_down_arrow"
android:paddingLeft="10dp"
/>
<EditText
android:id="#+id/area"
android:background="#android:color/white"
android:hint="Area"
android:gravity="center|left"
android:padding="10dp"
android:textSize="14sp"
android:textColorHint="#000000"
android:layout_width="match_parent"
android:layout_height="40dp"
android:singleLine="true"
android:imeOptions="actionNext"
android:layout_marginBottom="10dp"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2">
<EditText
android:id="#+id/zipCode"
android:background="#android:color/white"
android:hint="Zip Code"
android:layout_weight="1"
android:gravity="center|left"
android:padding="10dp"
android:textSize="14sp"
android:textColorHint="#000000"
android:layout_width="0dp"
android:layout_height="40dp"
android:singleLine="true"
android:imeOptions="actionNext"
android:layout_marginRight="10dp"/>
<EditText
android:id="#+id/city"
android:background="#android:color/white"
android:hint="City"
android:layout_weight="1"
android:gravity="center|left"
android:padding="10dp"
android:textSize="14sp"
android:singleLine="true"
android:imeOptions="actionDone"
android:textColorHint="#000000"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/tab1_next"
android:layout_width="150dp"
android:layout_height="40dp"
android:text="NEXT"
android:layout_below="#+id/product_location_layout"
android:layout_margin="20dp"
android:layout_alignParentRight="true"
android:background="#color/next_button"
android:textColor="#android:color/white"
android:layout_marginBottom="20dp"
/>
</RelativeLayout>
</android.support.v4.widget.NestedScrollView>
Set the layout parameters again(width and height), right after adding the view. This worked for me.
if the parent View is a FrameLayout, then do something like this:
ImageView view = (ImageView) LayoutInflater.from(activity).inflate(R.layout.image_object_view, null);
imageObjectsHolder.addView(view);
FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
view.setLayoutParams(param);
My problem was fixed by seting layout_width to some specific dp.
So changing from "wrap content" or "match parent"
to
android:layout_width="300dp"
will fix it, but i know it's not solution for all cases. But maybe you have some parent width, so you can apply the width to the textview.
height leave with wrap_content, and it will work.

Categories

Resources