Simple image gallery with HorizontalScrollView - java

I'm writing an image gallery with horizontal scrolling. Images must be added programatically.
I use a custom horizontal scroll view to process and add images as in the following code:
public void setViewList(Integer linearLayoutId, Integer[] imageIdList,
Activity activity) {
displayMetrics = ImageUtils.getDisplayMetric(activity);
LinearLayout ll = (LinearLayout) findViewById(linearLayoutId);
for (Integer imgId : imageIdList) {
ImageView imageView = new ImageView(getContext());
imageView.setImageResource(imgId);
imageView.setScaleType(ImageView.ScaleType.MATRIX);
Integer[] displayMetrics = ImageUtils.getDisplayMetric(activity);
ImageUtils.scaleImage(imageView, displayMetrics[0], displayMetrics[1]);
Integer[] dstDimension = ImageUtils.createDimension();
ImageUtils.getImageSize(imageView, dstDimension);
getImageSizeList().add(dstDimension);
ll.addView(imageView);
}
}
As you can see I scale an image with use the following method (call ImageUtils.scaleImage(imageView, displayMetrics[0], displayMetrics[1])):
public static void scaleImage(ImageView imView, int screenWidth, int screenHeight) {
Drawable temp = imView.getDrawable();
Bitmap imBitmap = ((BitmapDrawable)temp).getBitmap();
int imWidth = imBitmap.getWidth();
int imHeight = imBitmap.getHeight();
float xScale = ((float) screenWidth) / imWidth;
float yScale = ((float) screenHeight) / imHeight;
float scale = xScale <= yScale ? xScale : yScale;
Matrix scaleMatrix = new Matrix();
scaleMatrix.postScale(scale, scale);
Bitmap scBitmap = Bitmap.createBitmap(imBitmap, 0, 0, imWidth, imHeight, scaleMatrix, true);
BitmapDrawable scDrBitmap = new BitmapDrawable(imView.getResources(), scBitmap);
imView.setImageDrawable(scDrBitmap);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
layoutParams.gravity = Gravity.CENTER;
imView.setLayoutParams(layoutParams);
}
My main.xml layout is pretty simple:
<?xml version="1.0" encoding="utf-8"?>
<android.lessons.custom_horizontal_scroll.CustomHorizontalScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/horizontalScrollView"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout android:orientation="horizontal"
android:id="#+id/mainLayout"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.lessons.custom_horizontal_scroll.CustomHorizontalScrollView>
Where the android.lessons.custom_horizontal_scroll.CustomHorizontalScrollView is implementation of a simple custom HorizontalScrollView.
For testing I use Samsung Galaxy S3 and images with the following resolution: (1) 1290*990 (2) 1221*900. What it looks like:
In many cases everything is displayed fine but from time to time I get the wrong result: the first image divides a screen with the following one at app start time and I don't have any idea why it happens.
Thanks for help.

I think you should use ViewPager from the support library v4 rather than this custom horizontal scroll view in this case. It's designed for that purpose.
Here is how to use it https://developer.android.com/training/animation/screen-slide.html.

The problem was resolved with use gravity = Gravity.FILL_HORIZONTAL | Gravity.CENTER_VERTICAL, that i set programmatically on a image view (method ImageUtils.scaleImage).

Related

How to implement re-sizing a cardview programatically in kotlin

Hi every one I am facing an issue while trying to expand the height of card view programatically in kotlin. I have tried to fix this by following some web resources, but those failed.
val layout = findViewById<CardView>(R.id.listGroupCardView)
val params: ViewGroup.LayoutParams = layout.layoutParams
params.height = 100
layout.layoutParams = params
Resulting in "Attempt to invoke virtual method 'android.view.ViewGroup$LayoutParams androidx.cardview.widget.CardView.getLayoutParams()' on a null object reference"
My code snippets are:
deviceHeight in 1800..2000 -> {
Log.d(tag, "Inside setUIComponents device height is $deviceHeight")
enterUniqueCode.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16F)
enterUniqueCode.height= 300
bearingImg.layoutParams.width = 350
bearingImg.layoutParams.height= 350
bearingImg.updatePadding(top=15)
etBarcode.height= 70
indicator.updatePadding(top=0)
etBarcode.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25F)
val param = etBarcode.layoutParams as ViewGroup.MarginLayoutParams
param.setMargins(0,45,0,7)
etBarcode.layoutParams = param
//etBarcode.updatePadding(top = 25)
cvSubmit.layoutParams.height= 150
btnSubmit.layoutParams.height= 150
Log.d(tag, "btnSubmit.height is : ${btnSubmit.height}")
btnSubmit.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25F)
llUniqueCode.layoutParams.height= 250
totalEarningImage.layoutParams.width= 150
totalEarningImage.layoutParams.height= 150
totalEarnings.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15F)
tvTotalPointsEarned.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15F)
llTotalEarnings.layoutParams.height = 150
productCatalogueImage.layoutParams.height = 150
productCatalogueImage.layoutParams.width = 150
productCatalogueImage.updatePadding(top=2)
transactionHistory.layoutParams.height = 150
transactionHistory.layoutParams.width = 150
transactionHistory.updatePadding(top=2)
referAFriend.layoutParams.height = 150
referAFriend.layoutParams.width = 150
referAFriend.updatePadding(top=2)
llBearing.updatePadding(top=12)
}
Here, before the brace ends, I have to resize the height of cardview of the layout which is list_group.xml, in this case here, And the list_group.xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="72dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:id="#+id/listGroupCardView"
android:layout_height="#dimen/dp_48"
android:elevation="8dp"
card_view:cardCornerRadius="6dp"
card_view:cardElevation="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listGroup"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView>
............
</ImageView>
<TextView>
............
</TextView>
</LinearLayout>
</CardView>
</LinearLayout>
I need help to figure out how to re-size this list_group's cardview programatically using kotlin
Set new layout params to the layout ,because the current layout params is null
val layout = findViewById<CardView>(R.id.listGroupCardView)
val params = ViewGroup.LayoutParams (
ViewGroup.LayoutParams.MATCH_PARENT,
100
)
layout.layoutParams = params

Set the margins of an imageView by programming inside a constraintLayout

I am trying to program the margin of the ImageView inside the ConstraniLayout2 with this code
ConstraintLayout.LayoutParams newLayoutParams = (ConstraintLayout.LayoutParams)
imageView.getLayoutParams();
newLayoutParams.topMargin = 140;
newLayoutParams.leftMargin = 400;
newLayoutParams.rightMargin = 0;
newLayoutParams.bottomMargin = 0;
imageView.setLayoutParams(newLayoutParams);
With this code I program the site of the imageView but of the entire screen of the smartphone.
How can I program the imageView to switch places with the constrainLayout2 references?
You can also try to set the margin using ConstraintSet.
Below is a snippet you can try
val constraintSet = ConstraintSet()
constraintSet.clone(constraintLayoutId)
val marginTop = context.getDimension(10f)
constraintSet.setMargin(R.id. imageView, ConstraintSet.TOP, marginTop)
constraintSet.applyTo(constraintLayoutId)
fun Context.getDimension(value: Float): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, value, this.resources.displayMetrics).toInt()
}

get and set layout_margin java

I to want get and set margin of my LinearLayout from java. I do not want set like right,left, top, bottom etc. I just want set simple margin from all side. I know I can do it via XML but I do know how can I do it via java.
I have done via xml is like below
android:layout_margin="20dp"
Anyone can please suggest me how can I do it via java?
To set margin to the view you can use this code:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
To get the margin of view use this code
View view = findViewById(...) //or however you need it
LayoutParams lp = (LayoutParams) view.getLayoutParams();
// margins are accessible via
lp.leftMargin;
lp.rightMargin;
lp.topMargin;
lp.bottomMargin;
// perhaps ViewGroup.MarginLayoutParams will work for you. It's a base class for //other LayoutParams.
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
Note: Sorry for using snippet...
It will work like a charm...
You can use following code to do so.
LinearLayoutview ll= findViewById(R.id.linearLayout); //or however you need it
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) ll.getLayoutParams();
margins are accessible via
lp.leftMargin;
lp.rightMargin;
lp.topMargin;
lp.bottomMargin;
Now you can use the code
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.setMargins(20,20,20,20);
ll.setLayoutParams(params);
Need use type of: MarginLayoutParams
Try this:
MarginLayoutParams params = (MarginLayoutParams) vector8.getLayoutParams();
params.width = 200; params.leftMargin = 100; params.topMargin = 200;
Code Example for MarginLayoutParams:
http://www.codota.com/android/classes/android.view.ViewGroup.MarginLayoutParams

TextView - Move view to end

I have a TextView with multiple lines. How can I determine the space at the end to know if a view fits in there?
Example:
--------------------
| I am a multiline |
| text that has |
| space at the |
| end. <View>|
--------------------
--------------------
| I am a multiline |
| text that has |
| not enough space |
| at theeee end. |
| <View>|
--------------------
So I want my view to be in the bottom right corner, it should not overlay the text, but right of it if there is enough space
Basically, you need to see where does the last line's right (y-coordinate) reaches, and then calculate if the other view can fit the rest of the space exists.
I did a sample here with 2 textviews, but it can be applied to any view you wish.
The xml is pretty straight farward, nothing out of the ordinary.
<?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">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kasjdf as df asd aasdfasdff as dfa sd sdf as df asd fa sd fa sdf as dfanas,df askdjfasjdf lkajsldkf jlaksjdfajsdkfj alskdj fklasjdflkasjdlkfdflk ajskldf" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="attached text"
android:textColor="#android:color/holo_blue_dark" />
</RelativeLayout>
The catch here, after text1 and text2 are drawn to in the layout, i'm calculating where does the last line of text1 reaches, and together with the width of text2 - see if it can fit the screen's width.
Only after text1 and text2 are drawn, i can check the width and right position, so i'm waiting for them both in setText2Position.
The catch here - adding rules to text2 according to the calculation described above.
If you have margins and padding to your views, it needs to be calculated as well fe, if text2 has padding, the check should be :
lastLineRight + text2.getWidth() + text2.getPaddingRight() + text2.getPaddingLeft() > screenWidth
public class MainActivity extends AppCompatActivity {
private boolean[] areBothViewsDrawn = {false, false};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text1 = (TextView) findViewById(R.id.text1);
final TextView text2 = (TextView) findViewById(R.id.text2);
text1.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
text1.getViewTreeObserver().removeGlobalOnLayoutListener(this);
areBothViewsDrawn[0] = true;
setText2Position(text1, text2);
}
});
text2.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
text2.getViewTreeObserver().removeGlobalOnLayoutListener(this);
areBothViewsDrawn[1] = true;
setText2Position(text1, text2);
}
});
}
private void setText2Position(TextView text1, TextView text2) {
if (!areBothViewsDrawn[0] || !areBothViewsDrawn[1])
return;
int lineCount = text1.getLayout().getLineCount();
float lastLineRight = text1.getLayout().getLineRight(lineCount - 1);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screenWidth = size.x;
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) text2.getLayoutParams();
if (lastLineRight + text2.getWidth() > screenWidth) {
//The width of the last line of text1 is too long for the text2 to fit, so text2 must be in another line
params.addRule(RelativeLayout.BELOW, text1.getId());
} else {
//The width of the last line of text1 and text2 smaller then the application's width, so text2 can be in the same line as text1
params.addRule(RelativeLayout.ALIGN_BOTTOM, text1.getId());
}
}
}
Here are some poc's for my code :
I think this question needs more context. (just curious to why you'd want to do this)
Something like this is possible and would be easier if the TextView had a set width/height defined in the XML. If you're just dynamically getting the information there's some steps you'd have to take to make sure you're getting the correct measurements.
One approach I'm thinking would be to get the entire TextView's width, and get the difference between that and the actual text's width (perhaps a combination of getLineCount()/getLineBounds(int, Rect?) and getTextScaleX()?). Then convert it to dp.

Set big image to background

I got current wallpaper as below:
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
now my current wallpaper (1152 X 1536)
I try to put it as background to activity but in width does not as screen width.
ImageView rv = (ImageView) findViewById(R.id.main);
rv.setBackgroundDrawable(wallpaperDrawable);
how I do it?
please help me.
thanks in advance
Did you set your RelativeLayout size is match_parent?
Then you can set Image fit to width side programmatically :
int width = getWindowManager().getDefaultDisplay().getWidth(); //get window width
yourIMG.getLayoutParams().width = width; // set Image width = window width
goto your xml for the current activity:
in that under the LinearLayout or Relative Layout add this line :
android:background = "#drawable/img_name"
and add the image to your drawable.

Categories