How to display label using Slider of Material component? - java

I am using the Slider of Material component:
https://github.com/material-components/material-components-android/blob/master/docs/components/Slider.md
I am trying to display a label when the thumb is moving, which seem to be supported with the labelFormatter attribute.
here is what my code looks like:
Slider s = new Slider(context);
s.setLabelFormatter(new Slider.LabelFormatter() {
#NonNull
#Override
public String getFormattedValue(float value) {
return "MY STRING";
}
});
When I go line by line with debugger it goes through this function:
private void drawLabelText(#NonNull Canvas canvas, int width, int top) {
labelTextPaint.getTextBounds(labelText, 0, labelText.length(), labelTextBounds);
int left = trackSidePadding + (int) (thumbPosition * width) - labelTextBounds.width() / 2;
canvas.drawText(labelText, left, top - labelTextTopOffset - thumbRadius, labelTextPaint); }
but no text is displayed only the slider...
I am kind of new in androïd and I am surely missing something.
Thanks for help :)
EDIT 1:
Here is the whole code simplified :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CoordinatorLayout layout = new CoordinatorLayout(this);
setContentView(layout);
// I am Using Coordinator Layout for current activity so...
CoordinatorLayout.LayoutParams layoutParams = new CoordinatorLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//Setting gravity to CENTER
layoutParams.gravity = Gravity.CENTER;
Slider slider = new Slider(this);
slider.setLabelFormatter(new Slider.LabelFormatter() {
#NonNull
#Override
public String getFormattedValue(float value) {
return "MY STRING";
}
});
layout.addView(slider, layoutParams);
}
But still not working ...
output result
https://youtu.be/obV4K-Nxu-0
EDIT 2:
Updating Material component from version: '1.2.0-alpha02' to version: '1.2.0-alpha05' fixed the issue.

Actually i wanted to comment but because of Reputation Constraints i couldn't,
Looks like you are adding a view programatically in your activity. Here i have implemented new MaterialComponent Slider with LabelFormatter
ViewGroup group = findViewById("YOUR_ACTIVITY_LAYOUT");
// I am Using Coordinator Layout for current activity so...
CoordinatorLayout.LayoutParams layoutParams = new CoordinatorLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//Setting gravity to CENTER
layoutParams.gravity = Gravity.CENTER;
Slider slider = new Slider(this);
slider.setLabelFormatter(new Slider.LabelFormatter() {
#NonNull
#Override
public String getFormattedValue(float value) {
return "MY STRING";
}
});
group.addView(slider, layoutParams);
}
And then there you go...

Related

Reaction button like facebook in Android

I wanna make a reaction button like Facebook, so something like this
Now i manage to make something similar with a DialogFragment but I am having some trouble with the position of my dialog, this code sometimes works but some other time the dialog is placed in the wrong place. Can someone give me some advice or suggest me a better way to do this?
My Dialog Class
public class ReactionsFragment extends DialogFragment {
public static final String TAG = "ReactionsFragment";
private View paretnView;
public ReactionsFragment(View view, String reviewId,Reactionable reactedContent) {
this.paretnView = view;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_reactions, container, false);
initComponent(view);
setDialogPosition();
return view;
}
public void initComponent(View rootView) {...}
public void setDialogPosition() {
if (paretnView == null) {
return; // Leave the dialog in default position
}
int[] location = new int[2];
paretnView.getLocationOnScreen(location);
int sourceX = location[0];
int sourceY = location[1];
Window window = getDialog().getWindow();
window.setGravity(Gravity.TOP|Gravity.LEFT);
WindowManager.LayoutParams params = window.getAttributes();
params.x = sourceX - dpToPx(0);
params.y = sourceY - dpToPx(110);
window.setAttributes(params);
}
public int dpToPx(float valueInDp) {
DisplayMetrics metrics = getActivity().getResources().getDisplayMetrics();
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
}
}
Use PopupWindow. I think this is exactly what you are looking for:
https://developer.android.com/reference/android/widget/PopupWindow
You can set the exact position for the popup to appear using this method

RelativeLayout addRule at BaseAdapter doesn't work very well

After one of rule is added to RelativeLayout, I get a don't very correct result. ID does not apply to element/is applied incorrectly. This affects at rules that must be bound to widget.
As a container, I use ListView and add objects to it through BaseAdapter. This obviously does not give desired result, but after reusing same widget that is returned back to the adapter and reused (element is guaranteed not changing again), rules starting working correctly.
#Override
protected void onCreate(Bundle state) {
super.onCreate(state);
ListView view = new ListView(this);
view.setBackgroundColor(Color.BLACK);
view.setId("files_list".hashCode());
view.setAdapter(new TestAdapter(this));
...
private class TestAdapter extends BaseAdapter {
...
#Override
public View getView(int position, View convertView, View parent) {
if(convertView == null) convertView = inflateView();
// only changes text & pictures, doesn't affecting display
manipulateItem(position, convertView);
return convertView;
...
private View inflateView() {
RelativeLayout layout = new RelativeLayout(context);
layout.setLayoutParams(new ViewGroup.LayoutParams(-1, -2));
ImageView icon = new ImageView(context);
icon.setBackgroundColor(Color.BLACK);
icon.setPadding(20, 20, 20, 20);
icon.setId("file_icon".hashCode());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(110, -1);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.rightMargin = 30;
layout.addView(icon, params);
...
LinearLayout additional = new LinearLayout(context);
additional.setOrientation(LinearLayout.VERTICAL);
additional.setGravity(Gravity.RIGHT);
additional.setBackgroundColor(Color.RED);
additional.setPadding(30, 0, 30, 0);
additional.setId(java.lang.String("additional_info").hashCode());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(-2, -2);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(additional, params);
...
LinearLayout uniqal = new LinearLayout(context);
uniqal.setOrientation(LinearLayout.VERTICAL);
uniqal.setBackgroundColor(Color.BLUE);
uniqal.setId("uniqal_info".hashCode());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(-2, -2);
// problem occurs here
params.addRule(RelativeLayout.LEFT_OF, additional.getId());
params.addRule(RelativeLayout.RIGHT_OF, icon.getId());
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(uniqal, params);
...
return layout;
}
This is what widget will looks like after first scrolling: elements after first drawing screen
And so, after scrolling and reusing same widget: working screen
After firstly 5 uses (so much got into my test screen), everything becomes fine. For the first time, views don't want to be attached by ID to another widget in any way. Is there a way around this?
Options for inflating layout from application .xml don't suit me
Manual update of layout helped me, however this doesn't work right away and my question remains relevant. Here is modified inflateView code:
private View inflateView() {
...
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(-2, -2);
params.addRule(RelativeLayout.LEFT_OF, additional.getId());
params.addRule(RelativeLayout.RIGHT_OF, icon.getId());
params.addRule(RelativeLayout.CENTER_IN_PARENT);
uniqal.post(new Runnable() {
public void run() {
uniqal.requestLayout();
}
});
layout.addView(uniqal, params);
...
return layout;
}

How to center text vertically in a TextView with Java code?

I know this question has been asked many times on SO. I have read most of them, but they don't work for me, so don't bother marking duplicates.
Here is my code, and what I have tried so far:
RelativeLayout container = new RelativeLayout(this.getContext());
TextView tv = new TextView(this.getContext());
tv.setText(txt); // a single digit like '3'
tv.setLines(1);
tv.layout(0, offsety, cellszie, offsety+cellsize);
tv.setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER);
tv.setGravity(Gravity.CENTER);
// I also tried CENTER_VERTIAL and the following line
// tv.setGravity(CENTER_VERTIAL| CENTER_HORIZONTAL);
// I also tried giving LayoutParams to tv like this:
// tv.setLayoutParams(new LayoutParams(cellsize, cellsize));
// tv.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
// tv.setLayoutParams(new LayoutParams(MATCH_PARENT, MATCH_PARENT));
container.addView(tv);
The character is horizontally centered, but it floats on the top of the TextView vertically. Setting gravity and LayoutParams doesn't change its behavior.
What should I do to make it center vertically?
use this class for VerticalTextView.
public class VerticalTextView extends TextView {
final boolean topDown;
public VerticalTextView(Context context, AttributeSet attrs){
super(context, attrs);
final int gravity = getGravity();
if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
setGravity((gravity&Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
topDown = false;
}else
topDown = true;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}
#Override
protected void onDraw(Canvas canvas){
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.drawableState = getDrawableState();
canvas.save();
if(topDown){
canvas.translate(getWidth(), 0);
canvas.rotate(90);
}else {
canvas.translate(0, getHeight());
canvas.rotate(-90);
}
canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
getLayout().draw(canvas);
canvas.restore();
}
}
you can do it like this
RelativeLayout container = new RelativeLayout(this.getContext());
View view = layoutInflater.inflate(R.layout.my_layout_file, null);
container.addView(view);
where R.layout.my_layout_file contains textview with gravity center. and here you can get object of textview like this
textviewObject = (TextView)view.findViewById(R.id.textViewId)
Try setting RelativeLayout.LayoutParams to you RelativeLayout
RelativeLayout.LayoutParams relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
container.setLayoutParams(relativeLayoutParams)
Then set the gravity for your TextView:
tv.setGravity(Gravity.CENTER);
Then add the view to your RelativeLayout:
container.addView(tv);

how to implement borders around menuitem in SwipeMenuListView

I am using the library com.baoyz.swipemenulistview every thing is working good i want borders around each menu items, so that even if all menu item background is white a grey border is around the each item separating each other.
After looking into the code i have found that this can be implemented in following function of SwipeMenuView.java
private void addItem(SwipeMenuItem item, int id) {
LayoutParams params = new LayoutParams(item.getWidth(),
LayoutParams.MATCH_PARENT);
LinearLayout parent = new LinearLayout(getContext());
parent.setId(id);
parent.setGravity(Gravity.CENTER);
parent.setOrientation(LinearLayout.VERTICAL);
parent.setShowDividers(LinearLayout.SHOW_DIVIDER_BEGINNING);
parent.setLayoutParams(params);
parent.setBackgroundDrawable(item.getBackground());
parent.setOnClickListener(this);
addView(parent);
if (item.getIcon() != null) {
parent.addView(createIcon(item));
}
if (!TextUtils.isEmpty(item.getTitle())) {
parent.addView(createTitle(item));
}
}
As i am newbie for android world, i am unable to find the way to to draw border around menu item. Which function/method to look for in LinearLayout that have the capability to draw borders. Or how to draw border as shown
Ide : Android Studio 2.2.3
Link to library :
SwipeMenuListView Github
UPDATE
I have added GradeintDrawable to the function now border is there but here i cannot pass item.getBackground which will return (Drawable). How to set GradientDrawable.setColor (int color); with item.getBackground which will return Drawable;
private void addItem(SwipeMenuItem item, int id) {
LayoutParams params = new LayoutParams(item.getWidth(),
LayoutParams.MATCH_PARENT);
GradientDrawable drawable = new GradientDrawable();
drawable.setShape(GradientDrawable.RECTANGLE);
drawable.setStroke(1, Color.BLACK);
drawable.setCornerRadius(1);
//drawable.setColor(Color.GRAY); here i have to pass item.getBackground();
//like :
drawable.setColor(item.getBackground); //error because getBackground is of type drawable;
LinearLayout parent = new LinearLayout(getContext());
parent.setId(id);
parent.setGravity(Gravity.CENTER);
parent.setOrientation(LinearLayout.HORIZONTAL);
parent.setLayoutParams(params);
//parent.setBackgroundDrawable(item.getBackground());
parent.setBackgroundDrawable(drawable);
parent.setOnClickListener(this);
addView(parent);
if (item.getIcon() != null) {
parent.addView(createIcon(item));
}
if (!TextUtils.isEmpty(item.getTitle())) {
parent.addView(createTitle(item));
}
}

How to animate the height of a View?

i have a method i created that is called throughout my project, i made it because i have a Crouton (toast) that tells a user to activate there account, or it will also alert them when there is no valid internet connection... And i dont want it to interfere with the top of my View because theres user actions that are important there. Im using a RelativeLayout
First off, this piece of code doesnt work anyways, but as i was fixing it i realized my bar i have at the bottom to switch between different Activities is now gone because it was slid down, im thinking i can just resize the hieght.
can anyone point me int he right direction for two things, one resizing height instead of sliding the whole view down, and two, help me fix the crash im getting, which occurs on setLayoutParam
i call this like this teknoloGenie.slideViewDown("100", findViewById(R.id.RootView));
public void slideViewDown(final String distX, final View view) {
final TranslateAnimation slideDown = new TranslateAnimation(0, 0, 0, Float.parseFloat(distX));
slideDown.setDuration(500);
slideDown.setFillEnabled(true);
slideDown.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override public void onAnimationEnd(Animation animation) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)view.getLayoutParams();
params.addRule(RelativeLayout.CENTER_HORIZONTAL, -1);
params.setMargins(0, view.getTop()+Integer.parseInt(distX), 0, 0);
view.setLayoutParams(params);
view.requestLayout();
}
});
view.startAnimation(slideDown);
}
If you want to animate the height of a View, you need to write your own custom-animation and modify the LayoutParams of your animated view.
In this example, the animation animates the height of the animated View.
This is how it could look like:
public class ResizeAnimation extends Animation {
private int startHeight;
private int deltaHeight; // distance between start and end height
private View view;
/**
* constructor, do not forget to use the setParams(int, int) method before
* starting the animation
* #param v
*/
public ResizeAnimation (View v) {
this.view = v;
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
view.getLayoutParams().height = (int) (startHeight + deltaHeight * interpolatedTime);
view.requestLayout();
}
/**
* set the starting and ending height for the resize animation
* starting height is usually the views current height, the end height is the height
* we want to reach after the animation is completed
* #param start height in pixels
* #param end height in pixels
*/
public void setParams(int start, int end) {
this.startHeight = start;
deltaHeight = end - startHeight;
}
#Override
public boolean willChangeBounds() {
return true;
}
}
In code, create a new Animation and apply it to the RelativeLayout that you want to animate:
View v = findViewById(R.id.youranimatedview);
// getting the layoutparams might differ in your application, it depends on the parent layout
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) v.getLayoutParams();
ResizeAnimation a = new ResizeAnimation(v);
a.setDuration(500);
// set the starting height (the current height) and the new height that the view should have after the animation
a.setParams(lp.height, newHeight);
v.startAnimation(a);
To your LayoutParams problem:
My guess is that you are getting a ClassCastException because you are not using the correct LayoutParams class. If your animated view for example is contained by a RelativeLayout, you can only set RelativeLayout.LayoutParams to it. If your View is contained by a LinearLayout, you can only set LinearLayout.LayoutParams for your View.

Categories

Resources