Set the margins of an imageView by programming inside a constraintLayout - java

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()
}

Related

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

How to dynamically insert a relative layout into a table layout

I am a newbie to Android Programming. I want a table layout that has 3 rows and 3 columns(may be I will dynamically change these numbers), with each table row having a relative layout inside it. This is similar like the view shown in Google Play Store which shows the new arrivals on Play etc.. I have tried using buttons to achieve this. But I want to inflate an xml file, having Relative Layout as the root with an ImageView and TextView. Is this possible? Or what is the best way to acheive this type of layout? Also, how to find the imageview and textview of the inflated layout so that I can programatically add properties to it. This is what I have tried.
private void populateCategoryGrid() {
TableLayout categoriesLayout;
TableRow row;
Button btn_category; int category_count = 12;
int NUM_ROW = category_count/3;
int NUM_COL = category_count/4;
for (int r=0;r<NUM_ROW;r++) {
row = new TableRow(this);
row.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.MATCH_PARENT,
1.0f
));
categoriesLayout.addView(row);
for (int c = 0; c <NUM_COL; c++) {
btn_category = new Button(this);
btn_category.setId(c);
btn_category.setPadding(0, 0, 0, 0);
btn_category.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.MATCH_PARENT,
1.0f
));
row.addView(btn_category);
}
}
}
You pretty much did all the work by looping and inflating buttons into rows. Few adjustments and you're done:
private void populateCategoryGrid() {
TableLayout categoriesLayout;
int category_count = 12;
int NUM_ROW = category_count/3;
int NUM_COL = category_count/4;
LayoutInflater inflater = LayoutInflater.from(this);
// Add rows
for (int r=0;r<NUM_ROW;r++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.MATCH_PARENT,
1.0f
));
// Add inflated layouts
for (int c = 0; c <NUM_COL; c++) {
// Inflate layout
RelativeLayout rl = (RelativeLayout) inflater.inflate(R.layout.rel_layout, null);
// Modify inflated layout
ImageView img = (ImageView) rl.findViewById(R.id.img);
img.setBackgroundColor(Color.RED);
TextView tv = (TextView) rl.findViewById(R.id.text);
tv.setText("Some text");
// Add the modified layout to the row
row.addView(rl);
}
// Add row to the table
categoriesLayout.addView(row);
}
}
A few notes:
You can use a local variable for each TableRow since once the row is done, you won't change anything inside of it
LayoutInflater.inflate returns the root view, in which you can findViewById any views located inside of it

Simple image gallery with HorizontalScrollView

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).

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.

Xcode image link ImageView into next View Controller

I have made a Xcode project for a tabbed application that displays images of color swatches in a Scrollview. How do I link One of the images in my scrollview to go to the next View Controller? Below is my code and pictures. So when you click on one of the images or swatch color in the scrollview it links to the New Controller.
I have multiple images that scroll down the page of the iPhone, Do I have to loop the images cause there are 24 images. I was able to make one button and link it to the next scene with the interface builder, But I can fit 5 images on the screen..
DecorsViewController_iPhone.h
#import <UIKit/UIKit.h>
#interface DecorsViewController_iPhone : UIViewController
{
IBOutlet UIScrollView *scrollViewDecors;
}
#property (nonatomic, retain) UIView *scrollViewDecors;
#end
DecorsViewController_iPhone.m
#import "DecorsViewController_iPhone.h"
#interface DecorsViewController_iPhone ()
#end
#implementation DecorsViewController_iPhone
#synthesize scrollViewDecors;
const CGFloat kScrollObjHeight = 81.5;
const CGFloat kScrollObjWidth = 320.0;
const NSUInteger kNumImages = 24;
- (void)layoutScrollImages
{
UIImageView *view = nil;
NSArray *subviews = [scrollViewDecors subviews];
// reposition all image subviews in a horizontal serial fashion
CGFloat curXLoc = 0;
CGFloat curYLoc = 0;
CGFloat curYSpace = 1;
for (view in subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, curYLoc);
view.frame = frame;
curYLoc += (curYSpace + kScrollObjHeight);
}
}
// set the content size so it can be scrollable
[scrollViewDecors setContentSize:CGSizeMake(([scrollViewDecors bounds].size.width), (kNumImages * kScrollObjHeight))]; // Vertical Option
}
- (void)viewDidLoad
{
self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
// 1. setup the scrollview for multiple images and add it to the view controller
//
// note: the following can be done in Interface Builder, but we show this in code for clarity
[scrollViewDecors setBackgroundColor:[UIColor blackColor]];
[scrollViewDecors setCanCancelContentTouches:NO];
scrollViewDecors.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollViewDecors.clipsToBounds = YES; // default is NO, we want to restrict drawing within our scrollview
scrollViewDecors.scrollEnabled = YES;
// pagingEnabled property default is NO, if set the scroller will stop or snap at each photo
// if you want free-flowing scroll, don't set this property.
// scrollView1.pagingEnabled = YES;
// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"Artwork_iPhone_Decors_Scrollview_%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[scrollViewDecors addSubview:imageView];
//[imageView release];
}
[self layoutScrollImages]; // now place the photos in serial layout within the scrollview
}
//- (void)dealloc
//{
// [scrollViewDecors release];
//
// [super dealloc];
//}
//- (void)viewDidLoad
//{
// [super viewDidLoad];
// // Do any additional setup after loading the view, typically from a nib.
//}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
#end
Firstly, you need to add a gesture recogniser to your view with something like:
UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(flipView:)];
[singleTapGestureRecognizer setNumberOfTapsRequired:1];
[self.view addGestureRecognizer:singleTapGestureRecognizer];
You then need to implement the 'flipView' method:
- (void)flipView:(UIPanGestureRecognizer *)recognizer {
[self performSegueWithIdentifier:#"textView" sender:self];
}
As you can see in my case, when the method is triggered I perform a segue (see below):
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"textView"])
{
//---Pass text to view
CGRect visibleRect;
visibleRect.origin = scrollView.contentOffset;
visibleRect.size = scrollView.bounds.size;
int number;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
number = visibleRect.origin.x / 768;
}
else {
number = visibleRect.origin.x / 320;
}
TextViewController *textViewController = segue.destinationViewController;
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
textViewController.text = [appDelegate.textArray objectAtIndex:number];
}
}
The 'number' variable is used to decide which image has been clicked, I divide the visible rects origin by the width of the screen in pixels to calculate which image has been pressed and therefore what data to send to my new view.
In your case, you would use the Y coordinate to perform a calculation to decide which colour has been pressed, possibly something like:
int number;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
number = visibleRect.origin.y / <height of each image on iPad in pixels>;
}
else {
number = visibleRect.origin.y / <height of each image on iPhone in pixels>;
}
Alternatively, you could use a UITableView and just populate the cells with the appropriate colour and then display the new view based on which cell was pressed.
EDIT
Use a UITableView, and populate each cell with your image using custom tableview cells. This is a much easier approach than what you are suggesting.
See these links:
adding images to UItableView
If using iOS 5 -
http://kurrytran.blogspot.co.uk/2011/10/ios-5-storyboard-uitableview-tutorial.html
if not -
http://www.iosdevnotes.com/2011/10/uitableview-tutorial/
You are overcomplicating this task massively, follow the above tutorials and you'll be done in no time. If this answer helped you, please mark it as correct.
You can customize your UIImageView. For example, MyImageView. Set its delegate to your main ScrollView and add UITapGestureRecognizer and TapDetecting Delegate methods.
You can implement in the MyImageView:
- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer {
// single tap
if ([_delegate respondsToSelector:#selector(myImageViewWasSingleTapped:)])
[_delegate myImageViewWasSingleTapped:self];
}
then in your main ScrollView(delegate of MyImageView):
- (void)myImageViewWasSingleTapped:(MyImageView *)miv {
AnotherViewController *asv = [[AnotherViewController alloc] initWithImage: miv];
[self.navigationController pushViewController: asv animated:YES];
[asv release];
}
You can use a button instead of a UIImageView, and set the button's image to your image. Your loop in viewDidLoad would be like this:
// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"Artwork_iPhone_Decors_Scrollview_%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIButton *imageButton = [[UIButton alloc] init];
[imageButton setImage:image forState:UIControlStateNormal];
[imageButton addTarget:self action:#selector(pushNextViewController:) forControlEvents:UIControlEventTouchUpInside];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = CGRectMake(0, 0, kScrollObjWidth, kScrollObjHeight);
imageButton.frame = rect;
imageButton.tag = i; // tag our images for later use when we place them in serial fashion
[scrollViewDecors addSubview:imageButton];
// Release imageButton unless you're using ARC
}
And then you'd need to define an action for imageButton, in this case I called it pushNextViewController:
- (void)pushNextViewController:(id)sender
{
UIViewController *yourNextViewController = // initialise your next view controller here
[self.navigationController pushViewController:yourNextViewController animated:YES];
}

Categories