move image with seekbar - android

How could I move image when scrolling seekbar? I want to move this indicator image when changing seekbar thumb position.
Here is image.

Some adjustments may need to be made depending upon your choice of image and/or its alignment with the seekbar. I am sure someone else here will come up with a better approach, but here's my take on it:
// Declare global variables
SeekBar sb;
LinearLayout.LayoutParams params;
Point p;
ImageView iv;
// Initialize the widgets
sb = (SeekBar) findViewById(....);
iv = (ImageView) findViewById(....);
// Since I added SeekBar and ImageView to a LinearLayout.
// Use LayoutParams for whichever container you use.
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
// Starting position
params.leftMargin = 0;
// Decide the value based on where you wish to place the image w.r.t the SeekBar
params.topMargin = ...;
iv.setLayoutParams(params);
// You will use this to get the width of the screen
p = new Point();
getWindowManager().getDefaultDisplay().getSize(p);
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// ((float)progress * p.x) / 100): "p.x" holds the screen's width.
// The expression computes the percentage of
// screen width given the "progress" value
// (progress * 0.5): This is being used to offset image position.
// I am using the offset because it seemed that the image
// was leading the SeekBar at higher progress values.
// You can try different values to see which one works best.
int measure = (int)((((float)progress * p.x) / 100) - (progress * 0.5));
// When "measure" will become equal to "p.x"(at progress = 100),
// the image will be outside the view when we set its "leftMargin".
// But, the image will start disappearing before that.
// When this situation comes, set the "leftMargin" to a maximum value
// which is the screen width - ImageView' width
if (p.x - measure < iv.getWidth()) {
params.leftMargin = p.x - iv.getWidth();
} else {
params.leftMargin = measure ;
}
// Set the "topMargin" to the value you decided upon before
params.topMargin = ...;
// Set LayoutParams
iv.setLayoutParams(params);
}
});
Edit (for user Shripal's comment) -- above the SeekBar (Y-axis):
layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp" > <!-- adjust this in java code -->
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/some_drawable" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="50" />
</RelativeLayout>
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

Here is the xml code
<SeekBar
android:id="#+id/seek_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:thumb="#drawable/seek_thumb_icon"
android:progressDrawable="#drawable/progress"/>
Heres the java code
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
mSeekBarProgressText.setText(String.valueOf(i) + " %");
mParcentValue = i;
setPercent(mDiscountPercentText , "-" + i , getResources().getDimension(R.dimen.discount_percent_text));
if (i > 0){
findMGTextView(R.id.card_without_discount).setVisibility(View.GONE);
} else {
findMGTextView(R.id.card_without_discount).setVisibility(View.VISIBLE);
}
int measure = (int)((((float)i * point.x) / 100) - (i * 0.5));
if (i < 50){
mSeekBarProgressText.setBackgroundResource(R.drawable.cucich1);
params.leftMargin = measure ;
} else {
mSeekBarProgressText.setBackgroundResource(R.drawable.cucich_reverse1);
params.leftMargin = measure - (mSeekBarProgressText.getWidth() + 20);
}
params.topMargin = 0;
mSeekBarProgressText.setLayoutParams(params);
findMGTextView(R.id.card_without_discount1).setLayoutParams(params);
}

Related

Gridview item programmatically from xml code

I want to add views (in this example, ImageViews) to a grid layout programmatically. My grid is fixed to 5 columns and 7 rows (35 items in total) and I don't want to add these 35 views in my xml so I want to do it programmatically. I'm struggling to find a conversion from xml to java/kotlin code for the attributes layout_width, layout_height, layout_columnWeight and layout_rowWeight so that the layout looks exactly the same as if I have defined the views in the xml. Can someone write the code for the views' layoutparams that matches these attributes?
<GridLayout
android:id="#+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="fill"
android:columnCount="5"
android:rowCount="7">
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
app:srcCompat="#drawable/ic_photo_camera"/>
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
app:srcCompat="#drawable/ic_photo_camera"/>
... //35 times the Image view
</GridLayout>
The previous xml would give me the next layout:
I tried the next one without success (Imageviews are showing too big and not fitting all inside the grid boundaries):
for(i in 1..35) {
val view = ImageView(context)
val params = GridLayout.LayoutParams(
GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL,1f),
GridLayout.spec(GridLayout.UNDEFINED,GridLayout.FILL,1f))
view.layoutParams = params
gridView.addView(view, 0)
}
Can you help me translate the xml into java/kotlin code? Thanks in advance
First step would be to create a view object
val image = ImageView()
image.setImageResource(resourceID)
Then you'll need to set layout attributes
val params = GridLayout.LayoutParams(x, y)
//x and y is your size, if you want something special you can do for instance LayoutParams.FILL_PARENT
You can also set size a bit later:
params.height = X
params.width = Y
Lastly you just add the view to the layout
gridView.addView(image)
Put that all inside a for loop and you're done. GridView would take care of placing the views.
Result :
Try something like this :
final int MAX_COLUMN = gridView.getColumnCount(); //5
final int MAX_ROW = gridView.getRowCount(); //7
final int itemsCount = MAX_ROW * MAX_COLUMN; //35
int row = 0, column = 0;
for (int i = 0; i < itemsCount; i++) {
ImageView view = new ImageView(this);
//Just to provide alternate colors
if (i % 2 == 0) {
view.setBackgroundColor(Color.RED);
} else {
view.setBackgroundColor(Color.GREEN);
}
GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(row, 1F), GridLayout.spec(column, 1F));
view.setLayoutParams(params);
gridView.addView(view);
column++;
if (column >= MAX_COLUMN) {
column = 0;
row++;
}
}
If you want specific width and height for your cells, then use :
params.width = 100; // Your width
params.height = 100; //your height

Keep text inside a textview centered during textsize animation

I am trying to animate the text inside a TextView to grow and change from black to green. The color change works perfectly, and the text size animates between the right sizes, but the text increases in size from the top left point. I would like the text to increase in size from the center. I have tried using .setGravity(Gravity.Center), .setPivotY()and .setPivotX(), and a few other solutions but nothing seems to be working. Also tried using. TranslateY but that seems to move the entire TextView rather than the just the text inside and was getting messy resetting the text position after.
Textview tv_CurrentWord = (TextView) findViewById(R.id.tv_currentWord);
final float defaultTextSize = tv_CurrentWord.getTextSize();
final float finalTextSize = defualtTextSize* 1.2f;
final float g = 155;
if (mValueAnimator.isRunning()){
mValueAnimator.cancel();
tv_CurrentWord.setTextSize(TypedValue.COMPLEX_UNIT_PX, defaultTextSize);
tv_CurrentWord.setTextColor(Color.BLACK);
}
mValueAnimator.removeAllUpdateListeners();
mValueAnimator.setDuration(200);
mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float animatedValue = (float) valueAnimator.getAnimatedValue();
tv_CurrentWord.setTextSize(TypedValue.COMPLEX_UNIT_PX, (finalTextSize-defaultTextSize)*animatedValue+defaultTextSize);
int color = Color.rgb(
0,
(int) (g*animatedValue)
,0);
tv_CurrentWord.setTextColor(color);
}
});
mValueAnimator.addListener(new AnimatorListenerAdapter()
{
#Override
public void onAnimationEnd(Animator animation)
{
mCurrentWord = "";
tv_CurrentWord.setTextSize(TypedValue.COMPLEX_UNIT_PX,
defaultTextSize);
tv_CurrentWord.setTextColor(Color.BLACK);
tv_CurrentWord.setText(mCurrentWord);
}
});
mValueAnimator.start();
and the XML. The LinearLayout container was a recent addition to try to keep the text centered, but I am not sure it is needed.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/current_word_height"
android:layout_below="#+id/rl_players_and_scores"
android:id="#+id/ll_current_word_container">
<TextView
android:id="#+id/tv_currentWord"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:ellipsize="start"
android:gravity="center"
android:singleLine="true"
android:textSize="40sp"
android:textStyle="bold" />
</LinearLayout>
I ended up figuring this out. Posting here for anyone else who might have the same question. I used .setTranslationY and .setY. The XML LinearLayout wrapper around the TextView was important because it allowed the TextView to move without throwing off other elements in the parent layout that were positioned off of it. .setTranslationY was used to offset the increasing text size in the TextView. Since .setTextSize(px) and .setTranslationY(px) both take pixels the Y translation just had to be half the change in text size. .setY() was used in the animation end, or on restart of the animation to reset the TextView to the original position. .setTranslationX was not needed because the text actually stays centered horizontally during the animation.
Textview tv_CurrentWord = (TextView) findViewById(R.id.tv_currentWord);
float currentWordYPosition = tv_CurrentWord.getY();
final float defaultTextSize = tv_CurrentWord.getTextSize();
final float finalTextSize = defualtTextSize* 1.2f;
final float g = 155;
if (mValueAnimator.isRunning()){
mValueAnimator.cancel();
tv_CurrentWord.setTextSize(TypedValue.COMPLEX_UNIT_PX,
defaultTextSize);
tv_CurrentWord.setTextColor(Color.BLACK);
tv_CurrentWord.setY(currentWordYPosition);
}
mValueAnimator.removeAllUpdateListeners();
mValueAnimator.setDuration(200);
mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float animatedValue = (float) valueAnimator.getAnimatedValue();
tv_CurrentWord.setTextSize(TypedValue.COMPLEX_UNIT_PX,
(finalTextSize-defaultTextSize)*animatedValue+defaultTextSize);
tv_CurrentWord.setTranslationY(-1*(finalTextSize-
defaultTextSize)*animatedValue/2);
int color = Color.rgb(
0,
(int) (g*animatedValue)
,0);
tv_CurrentWord.setTextColor(color);
}
});
mValueAnimator.addListener(new AnimatorListenerAdapter()
{
#Override
public void onAnimationEnd(Animator animation)
{
mCurrentWord = "";
tv_CurrentWord.setTextSize(TypedValue.COMPLEX_UNIT_PX,
defaultTextSize);
tv_CurrentWord.setTextColor(Color.BLACK);
tv_CurrentWord.setText(mCurrentWord);
tv_CurrentWord.setY(currentWordYPosition);
}
});
mValueAnimator.start();

Xamarin Android - How prevent text move during textview animation

I have to do some animation in my application but i have a problem with textview.
I need to animate a textview and make it compare from right corner.
this is my layout:
<RelativeLayout
android:id="#+id/ThirdPartBottomLayout"
android:layout_width="2000dp"
android:layout_height="250dp"
android:layout_alignParentBottom="true"
android:background="#color/RedTA"
android:paddingTop="20dp"
android:paddingBottom="80dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/ThirdPartText1"
android:textSize="20dp"
android:textColor="#ffffff"
android:lines="1"
android:text="#string/Onboarding_Page3_Text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" />
<TextView
android:id="#+id/ThirdPartText2"
android:textSize="16dp"
android:textColor="#ffffff"
android:layout_below="#+id/ThirdPartText1"
android:text="#string/Onboarding_Page3_Text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center" />
</RelativeLayout>
</RelativeLayout>
and this is where I inizialize variable:
int widhtR1 = 0;
if (ThirdPartText1.Width > WidthPixel - PixelsToDp(50))
widhtR1 = WidthPixel - PixelsToDp(50);
else
widhtR1 = ThirdPartText1.Width;
lp = new RelativeLayout.LayoutParams(widhtR1,
ThirdPartText1.Height);
lp.LeftMargin = WidthPixel;
ThirdPartText1LeftMargin = (WidthPixel - widhtR1) / 2;
ThirdPartText1.LayoutParameters = lp;
int widhtR2 = 0;
if (ThirdPartText2.Width > WidthPixel - PixelsToDp(50))
widhtR2 = WidthPixel - PixelsToDp(50);
else
widhtR2 = ThirdPartText2.Width;
lp = new RelativeLayout.LayoutParams(widhtR2,
ThirdPartText2.Height);
lp.LeftMargin = WidthPixel;
lp.TopMargin = PixelsToDp(10);
lp.AddRule(LayoutRules.Below, Resource.Id.ThirdPartText1);
ThirdPartText2LeftMargin = (WidthPixel - widhtR2) / 2;
ThirdPartText2.LayoutParameters = lp;
To animate i use a ValueAnimator that move LeftMargin from WidhtPixel to the minium left margin of textview.
And I do with this code.
ThirdPartText1Animator = ValueAnimator.OfInt(1);
ThirdPartText1Animator.SetDuration(
ThirdPartText1AnimatorDuration);
ThirdPartText1Animator.SetInterpolator(new
AccelerateDecelerateInterpolator());
var lpTxt1 =
(RelativeLayout.LayoutParams)ThirdPartText1.LayoutParameters;
ThirdPartText1Animator.Update += (sender, e) =>
{
int val = (int)e.Animation.AnimatedValue;
Console.WriteLine("VAL TXT1:" + val);
lpTxt1.LeftMargin = WidthPixel - (int)((WidthPixel -
ThirdPartText1LeftMargin) * (val / 100f));
ThirdPartText1.LayoutParameters = lpTxt1;
};
ThirdPartText2Animator = ValueAnimator.OfInt(1);
ThirdPartText2Animator.SetDuration(
ThirdPartText2AnimatorDuration);
ThirdPartText2Animator.SetInterpolator(new
LinearInterpolator());
var lpTxt2 =
(RelativeLayout.LayoutParams)ThirdPartText2.LayoutParameters;
ThirdPartText2Animator.Update += (sender, e) =>
{
int val = (int)e.Animation.AnimatedValue;
Console.WriteLine("VAL TXT2:" + val);
lpTxt2.LeftMargin = WidthPixel - (int)((WidthPixel -
ThirdPartText2LeftMargin) * (val / 100f));
ThirdPartText2.LayoutParameters = lpTxt2;
};
/*** START WITH ****/
ThirdPartText1Animator.SetIntValues(0, 100);
ThirdPartText1Animator.Start();
ThirdPartText2Animator.SetIntValues(0, 100);
ThirdPartText2Animator.Start();
And here comes the problem when the animation start, text view compare from right but text will move to fit the textview dimension on screen instead of stay blocked on textview real dimension.
How could I avoid to make text move inside a textview.
Hope my information is enough and sorry for my bad english.
EDIT
WidthPixel = Resources.DisplayMetrics.WidthPixels;
AccelerateDecelerateInterpolator is an Interpolator Android.Views.Animation
Full classes
OnboardingPage.cs
OnboardingPageLayout.axml
Thanks in advance.
Matteo.
For everyone have the same problem i figured out a solution.
In a first time i use left margin to make textview compare, so when application start i set left margin to width of screen and when i need to make it appear i reduce left margin.
It seems that if you change somethings of textview it been forced to redraw everythings so also widht and height change.
To avoid this problem I create a layout and put textview inside it and use the same trick of left margin to layout instead on textview and everythings work.
Sorry for my bad english.
Hope that should be helpful for someone.

Android make continues scrolling text within single view in repeat mode

I am trying to implement ticker board where you can see all ticker in scrolling mode check below image,
now I want continue scrolling for example
in #user5 after some space and start again with this same value no blank area like in init space
I want like this
scrolling text from one user 3 hours #user3 <some space> scrolling text from...
sorry for bad english
here is my code
View view = parent_layout.getChildAt(index);
// measures the unconstrained size of the view
// before it is drawn in the layout
view.measure(View.MeasureSpec.UNSPECIFIED,
View.MeasureSpec.UNSPECIFIED);
// takes the unconstrained width of the view
float width = view.getMeasuredWidth();
float height = view.getMeasuredHeight();
// gets the screen width
view.setLayoutParams(new LinearLayout.LayoutParams((int) width,
(int)height));
Log.e("contact details","width and screenwidth are" + width + "/"
+ screenWidth + "///" + view.getMeasuredWidth());
// performs the calculation
toXDelta = width - (screenWidth - 0);
// sets toXDelta to -300 if the text width is smaller that the
// screen size
if (toXDelta < 0) {
toXDelta = 0 - screenWidth;// -300;
} else {
toXDelta = 0 - screenWidth - toXDelta;// -300 - toXDelta;
}
// tickerList.add(view);
// animList.add(mAnimation);
// Animation parameters
mAnimation = new TranslateAnimation(screenWidth,
toXDelta, 0, 0);
mAnimation.setDuration(15000);
// mAnimation.setRepeatMode(Animation.RESTART);
mAnimation.setRepeatCount(Animation.INFINITE);
view.setAnimation(mAnimation);
My solution is just create double of string means appending current string with itself if the length is lower then screen width and using marquee feature in Textview.
private float screenWidth;
onCreate(){
TextView tv = (TextView)findViewById(R.id.textview);
Point outSize = new Point();
getWindowManager().getDefaultDisplay().getSize(outSize);
screenWidth = outSize.x;
StringBuilder ticker = new StringBuilder("This is my String");
do{
tv.setText(Html.fromHtml(ticker.toString()));
int w = ticker.length();
if(screenWidth>w){
ticker.append(" ");
ticker.append(tickerList.get(index));
tv.setText(Html.fromHtml(ticker.toString()));
}else
break;
}while(true);
}
xml code
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:singleLine="true"
android:textSize="18sp"
android:padding="5dp"
android:id="#+id/textView1">
</TextView>

Getting end position of the textview and imageview with respect to top of the screen

I have a bitmap and below it is a time line.
As an example consider the right side layout of the FIGURE.
All the bottom timelines (1, 2, 3...) are in the same height from top.
The timeline is a textview which has fixed layout height and width as it is defined in xml
like timeline 1 is defined as:
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/HView"
android:layout_marginLeft="18dp"
android:layout_marginTop="345dp"
android:textSize="14sp"
android:text="1"
android:textColor="#000000" />
However the bitmap height and width can vary as it is done programatically.
So in certain cases, the bitmap height increases enough to overlap the timeline. In other words,
the vertical position of bitmap increases with respect to the vertical position of the timeline.
I want to get:
1) the ended vertical position of bitmap with respect to top of the screen.
2) the ended vertical position of timeline with respect to top of the screen.
I tried to do the following:
TextView bottomTimeLine = (TextView) view.findViewById(R.id.textView1);
bottomTimeLine.getHeight(); //returns 0.
bottomTimeLine.getBottom(); //returns 0.
ImageView img = new ImageView(getActivity());
img.setImageDrawable(getResources().getDrawable(R.drawable.disp_bg));
img.getHeight(); //returns 0.
img.getBottom(); //returns 0.
As seen from the code, both the methods, getHeight() and getBottom() are returning height as 0.
How to get the height (view end position) of both with respect to top of the cell display ?
Hope this helps
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(
parentWidth / 2, parentHeight);
}
This is how it can be done:
final TextView bottomTimeLine = (TextView) view.findViewById(R.id.textView1);
final int[] timelineCoord = new int[2];
final int[] imgCoord = new int[2];
ViewTreeObserver vto = bottomTimeLine.getViewTreeObserver();
vto.addOnGlobalLayoutListener((new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
bottomTimeLine.getLocationOnScreen(timelineCoord);
Log.d(" bottomTimeLine H ", ""+timelineCoord[1]);
timelineHeight = timelineCoord[1];
}
}));
ViewTreeObserver vt1 = img.getViewTreeObserver();
vt1.addOnGlobalLayoutListener((new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
img.getLocationOnScreen(imgCoord);
imgHeight = imgCoord[1] + img.getHeight();
Log.d("Img H ", ""+imgHeight);
if(imgHeight < timelineHeight)
{
int heightDiff = imgHeight - timelineHeight ;
heightDiff = heightDiff + 3;
img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, heightDiff));
}
}
}));

Categories

Resources