Here you can see what my problem is, I made a custom TextView in Android, to add stroke to some scores. But so far I'm having 2 separated texts instead of one with stroke...
Here is my code:
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/game_end_share_relative_main"
android:layout_width="#dimen/share_width"
android:layout_height="#dimen/share_height"
android:background="#000000" >
<com.sharing.StrokeTextView
android:id="#+id/user_share_points"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:textColor="#color/primary"
android:layout_marginRight="16dp"
style="#style/SecondaryFontFamily"
android:textSize="70dp" />
And the custom TextView:
public class StrokeTextView extends TextView {
private int mStrokeColor;
private int mStrokeWidth;
private TextPaint mStrokePaint;
public StrokeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public StrokeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public StrokeTextView(Context context) {
super(context);
}
public void setStrokeColor(int color) {
mStrokeColor = color;
}
public void setStrokeWidth(int width) {
mStrokeWidth = width;
}
#Override
protected void onDraw(Canvas canvas) {
if (mStrokePaint == null) {
mStrokePaint = new TextPaint();
}
mStrokePaint.setTextSize(getTextSize());
mStrokePaint.setTypeface(getTypeface());
mStrokePaint.setFlags(getPaintFlags());
mStrokePaint.setStyle(Paint.Style.STROKE);
mStrokePaint.setColor(mStrokeColor);
mStrokePaint.setStrokeJoin(Paint.Join.ROUND);
mStrokePaint.setStrokeCap(Paint.Cap.ROUND);
mStrokePaint.setStrokeWidth(mStrokeWidth);
mStrokePaint.setShadowLayer(2.0f, 5.0f, 5.0f, Color.BLACK);
mStrokePaint.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/MikadoBlack.otf"));
String text = getText().toString();
canvas.drawText(text, getWidth() - (mStrokePaint.measureText(text) / 2), getBaseline(), mStrokePaint);
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/MikadoBlack.otf"));
super.onDraw(canvas);
}
}
Thanks for your help in advance :)
Jose
This is because the drawText in super class is drawing at a different position than yours. Try setting the content gravity to 'center' using View.setGravity(Gravity.CENTER) this may solve your problem. Also, if you are using padding on the view then you need to factor it in while calculating the origin for drawText method
int hPadding = getPaddingLeft()+getPaddingRight();
int contentAreaWidth = getWidth() - hPadding;
canvas.drawText(text, contentAreaWidth - (mStrokePaint.measureText(text) / 2), getBaseline(), mStrokePaint);
This would help in aligning the stroked text with the normal text drawn in the super class.
For instance I have a custom button and want to connect it to a SeekBar:
public class SeekBarButton extends ImageButton {
SeekBar seekBar;
public SeekBarButton(Context context) {
super(context);
}
public SeekBarButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SeekBarButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setSeekBar(SeekBar seekBar) {
this.seekBar = seekBar;
}
public SeekBar getSeekBar() {
return seekBar;
}
}
I can do it in the code:
sbb = (SeekBarButton) rootView.findViewById(R.id.minus_red);
sbRed = (SeekBar) rootView.findViewById(R.id.sbRed);
sbb.setSeekBar(sbRed);
But 8 buttons will give a lot of boilerplate, and I want something like:
<com.whatever.views.SeekBarButton
...
whatToPutHere:seekbar="#+id/sbRed" // like this? whatToPutHere?
android:id="#+id/minus_red" />
<SeekBar
android:id="#+id/sbRed"
... />
The easiest way to do this is to create a custom ViewGroup that contains both the Button and Seekbar. If you cannot do that, for any reason, here's a solution:
There are a few steps to make this work. First you must define a custom XML attribute that you can then reference and use.
Edit (or create) res/values/attrs.xml. Add:
<declare-styleable name="SeekBarButton">
<attr name="seekbarId" format="integer" />
</declare-styleable>
Then, in SeekBarButton, call this from the constructors:
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.SeekBarButton, defStyleAttr, 0);
mSeekbarId = a.getResourceId(R.styleable.SeekBarButton_seekbarId, 0);
a.recycle();
}
}
Finally, in your root ViewGroup of your layout file, add
xmlns:app="http://schemas.android.com/apk/res-auto"
Then,
<com.whatever.views.SeekBarButton
android:id="#+id/minus_red"
app:seekbarId="#+id/sbRed"
... />
<SeekBar
android:id="#+id/sbRed"
... />
Note You will need to call ((ViewGroup) getParent()).findViewById(mSeekbarId) in SeekBarButton to instantiate the SeekBar, but getParent() will be null in SeekBarButton constructors. So, delay findViewById() until you need the SeekBar.
I think you are close. In the first XML tag of your layout file (my example is a RelativeLayout) you need this reference to "custom":
<RelativeLayout
xmlns:custom="http://schemas.android.com/apk/res-auto">
Then farther down wherever your custom ImageButton is, you need this:
<com.whatever.views.SeekBarButton
...
custom:seekbar="#+id/sbRed"
android:id="#+id/minus_red" />
You will also need a seekBarButton.xml file in your project\res\values folder, if you didn't already know that.
I need to create text display like the Confide app. What I tried is to use FlowLayout but then I'm not able to get the row so that I can hide show row wise. There seems to be various options but kinda confused and not able to think wwat exactly to do... Like break the TextView and show in ListView but then I don't know how to form lines and create adapter.
Kindly help me if anyone knows this thing. I tried to search on Google but nothing fruitful.
At present I'm showing TextView using FlowLayout and showing hiding each TextView.
Try creating custom view like this one, lest call it CustomTextView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_marginTop="3dp"
android:background="#FF0000"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="3dp"
android:paddingBottom="3dp" >
<TextView
android:id="#+id/label"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible"
android:maxLines="1"
android:textColor="#FFFFFF" />
</LinearLayout>
java code:
public class CustomTextView extends FrameLayout implements View.OnClickListener {
public CustomTextView(Context context) {
super(context);
init(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
LayoutInflater.from(context).inflate(R.layout.custom_text_view, this);
setOnClickListener(this);
mLabelTextView = (TextView) findViewById(R.id.label);
}
#Override
public void onClick(View v) {
mLabelTextView.setVisibility(View.VISIBLE)
}
}
To add this views to your container view try something like this:
Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay();
mContainerView.removeAllViewsInLayout();
mContainerView.removeAllViews();
int maxWidth = display.getWidth() - 20;
LinearLayout.LayoutParams params;
LinearLayout newLL = new LinearLayout(getContext());
newLL.setLayoutParams(new LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));
newLL.setGravity(Gravity.LEFT);
newLL.setOrientation(LinearLayout.HORIZONTAL);
int widthSoFar = 0;
for (CustomTextView customTextView : CustomTextViewList) {
LinearLayout LL = new LinearLayout(getContext());
LL.setOrientation(LinearLayout.HORIZONTAL);
LL.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
LL.setLayoutParams(new ListView.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
customTextView.measure(0, 0);
params = new LinearLayout.LayoutParams(customTextView.getMeasuredWidth(), FrameLayout.LayoutParams.WRAP_CONTENT);
LL.addView(customTextView, params);
LL.measure(0, 0);
widthSoFar += customTextView.getMeasuredWidth();
if (widthSoFar >= maxWidth) {
mContainerView.addView(newLL);
newLL = new LinearLayout(getContext());
newLL.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));
newLL.setOrientation(LinearLayout.HORIZONTAL);
newLL.setGravity(Gravity.LEFT);
params = new LinearLayout.LayoutParams(LL.getMeasuredWidth(), LL.getMeasuredHeight());
newLL.addView(LL, params);
widthSoFar = LL.getMeasuredWidth();
} else {
newLL.addView(LL);
}
}
mContainerView.addView(newLL);
Example of CustomTextViewList (to answer your question from comment)
ArrayList<CustomTextView> CustomTextViewList = new ArrayList<CustomTextView>()
CustomTextViewList.add(new CustomTextView(context));
CustomTextViewList.add(new CustomTextView(context));
CustomTextViewList.add(new CustomTextView(context));
I got a class to extend NumberPicker component to introduce min & max value:
public class ExtendedNumberPicker extends NumberPicker {
public ExtendedNumberPicker(Context context) {
super(context);
}
public ExtendedNumberPicker(Context context, AttributeSet attrs) {
super(context, attrs);
processAttributeSet(attrs);
}
public ExtendedNumberPicker(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
processAttributeSet(attrs);
}
private void processAttributeSet(AttributeSet attrs) {
//This method reads the parameters given in the xml file and sets the properties according to it
this.setMinValue(attrs.getAttributeIntValue(null, "min", 0));
this.setMaxValue(attrs.getAttributeIntValue(null, "max", 0));
}
}
I put it into layout:
<com.example.myapp.component.ExtendedNumberPicker
android:id="#+id/pick_hh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="16dp"
min="140"
max="200" />
In LogCat, it shows:
Tag Text
---------------------------
PropertyValuesHolder Can't find native method using JNI, use reflectionjava.lang.NoSuchMethodError: no method with name='setSelectorPaintAlpha' signature='(I)V' in class Lcom/example/myapp/component/ExtendedNumberPicker;
PropertyValuesHolder Couldn't find setter/getter for property selectorPaintAlpha with value type int
I know JNI is Java Native Interface, but I never use/see the property selectorPaintAlpha. What is it? How to resolve the issue?
I want to download an image (of unknown size, but which is always roughly square) and display it so that it fills the screen horizontally, and stretches vertically to maintain the aspect ratio of the image, on any screen size. Here is my (non-working) code. It stretches the image horizontally, but not vertically, so it is squashed...
ImageView mainImageView = new ImageView(context);
mainImageView.setImageBitmap(mainImage); //downloaded from server
mainImageView.setScaleType(ScaleType.FIT_XY);
//mainImageView.setAdjustViewBounds(true);
//with this line enabled, just scales image down
addView(mainImageView,new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
I accomplished this with a custom view. Set layout_width="fill_parent" and layout_height="wrap_content", and point it to the appropriate drawable:
public class Banner extends View {
private final Drawable logo;
public Banner(Context context) {
super(context);
logo = context.getResources().getDrawable(R.drawable.banner);
setBackgroundDrawable(logo);
}
public Banner(Context context, AttributeSet attrs) {
super(context, attrs);
logo = context.getResources().getDrawable(R.drawable.banner);
setBackgroundDrawable(logo);
}
public Banner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
logo = context.getResources().getDrawable(R.drawable.banner);
setBackgroundDrawable(logo);
}
#Override protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * logo.getIntrinsicHeight() / logo.getIntrinsicWidth();
setMeasuredDimension(width, height);
}
}
In the end, I generated the dimensions manually, which works great:
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = width * mainImage.getHeight() / mainImage.getWidth(); //mainImage is the Bitmap I'm drawing
addView(mainImageView,new LinearLayout.LayoutParams(
width, height));
I just read the source code for ImageView and it is basically impossible without using the subclassing solutions in this thread. In ImageView.onMeasure we get to these lines:
// Get the max possible width given our constraints
widthSize = resolveAdjustedSize(w + pleft + pright, mMaxWidth, widthMeasureSpec);
// Get the max possible height given our constraints
heightSize = resolveAdjustedSize(h + ptop + pbottom, mMaxHeight, heightMeasureSpec);
Where h and w are the dimensions of the image, and p* is the padding.
And then:
private int resolveAdjustedSize(int desiredSize, int maxSize,
int measureSpec) {
...
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
/* Parent says we can be as big as we want. Just don't be larger
than max size imposed on ourselves.
*/
result = Math.min(desiredSize, maxSize);
So if you have a layout_height="wrap_content" it will set widthSize = w + pleft + pright, or in other words, the maximum width is equal to the image width.
This means that unless you set an exact size, images are NEVER enlarged. I consider this to be a bug, but good luck getting Google to take notice or fix it. Edit: Eating my own words, I submitted a bug report and they say it has been fixed in a future release!
Another solution
Here is another subclassed workaround, but you should (in theory, I haven't really tested it much!) be able to use it anywhere you ImageView. To use it set layout_width="match_parent", and layout_height="wrap_content". It is quite a lot more general than the accepted solution too. E.g. you can do fit-to-height as well as fit-to-width.
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
// This works around the issue described here: http://stackoverflow.com/a/12675430/265521
public class StretchyImageView extends ImageView
{
public StretchyImageView(Context context)
{
super(context);
}
public StretchyImageView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public StretchyImageView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// Call super() so that resolveUri() is called.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// If there's no drawable we can just use the result from super.
if (getDrawable() == null)
return;
final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int w = getDrawable().getIntrinsicWidth();
int h = getDrawable().getIntrinsicHeight();
if (w <= 0)
w = 1;
if (h <= 0)
h = 1;
// Desired aspect ratio of the view's contents (not including padding)
float desiredAspect = (float) w / (float) h;
// We are allowed to change the view's width
boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
// We are allowed to change the view's height
boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
int pleft = getPaddingLeft();
int pright = getPaddingRight();
int ptop = getPaddingTop();
int pbottom = getPaddingBottom();
// Get the sizes that ImageView decided on.
int widthSize = getMeasuredWidth();
int heightSize = getMeasuredHeight();
if (resizeWidth && !resizeHeight)
{
// Resize the width to the height, maintaining aspect ratio.
int newWidth = (int) (desiredAspect * (heightSize - ptop - pbottom)) + pleft + pright;
setMeasuredDimension(newWidth, heightSize);
}
else if (resizeHeight && !resizeWidth)
{
int newHeight = (int) ((widthSize - pleft - pright) / desiredAspect) + ptop + pbottom;
setMeasuredDimension(widthSize, newHeight);
}
}
}
Setting adjustViewBounds to true and using a LinearLayout view group worked very well for me. No need to subclass or ask for device metrics:
//NOTE: "this" is a subclass of LinearLayout
ImageView splashImageView = new ImageView(context);
splashImageView.setImageResource(R.drawable.splash);
splashImageView.setAdjustViewBounds(true);
addView(splashImageView);
I've been struggling with this problem in one form or another for AGES, thank you, Thank You, THANK YOU.... :)
I just wanted to point out that you can get a generalizable solution from what Bob Lee's done by just extending View and overriding onMeasure. That way you can use this with any drawable you want, and it won't break if there's no image:
public class CardImageView extends View {
public CardImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CardImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CardImageView(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable bg = getBackground();
if (bg != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * bg.getIntrinsicHeight() / bg.getIntrinsicWidth();
setMeasuredDimension(width,height);
}
else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
In some cases this magic formula beautifully solves the problem.
For anyone struggling with this coming from another platform, the "size and shape to fit" option is handled beautifully in Android, but it's hard to find.
You typically want this combination:
width match parent,
height wrap content,
adjustViewBounds turned ON (sic)
scale fitCenter
cropToPadding OFF (sic)
Then it's automatic and amazing.
If you're an iOS dev, it's utterly amazing how simply, in Android, you can do "totally dynamic cell heights" in a table view .. err, I mean ListView. Enjoy.
<com.parse.ParseImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/post_image"
android:src="#drawable/icon_192"
android:layout_margin="0dp"
android:cropToPadding="false"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:background="#eff2eb"/>
I have managed to achieve this using this XML code only. It might be the case that eclipse does not render the height to show it expanding to fit; however, when you actually run this on a device, it properly renders and provides the desired result. (well at least for me)
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/whatever" />
</FrameLayout>
I did it with these values within a LinearLayout:
Scale type: fitStart
Layout gravity: fill_horizontal
Layout height: wrap_content
Layout weight: 1
Layout width: fill_parent
Everyone is doing this programmily so I thought this answer would fit perfectly here. This code worked for my in the xml. Im NOT thinking about ratio yet, but still wanted to place this answer if it would help anyone.
android:adjustViewBounds="true"
Cheers..
A very simple solution is to just use the features provided by RelativeLayout.
Here is the xml that makes it possible with standard Android Views:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:id="#+id/button_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentBottom="true"
>
<Button
android:text="button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<ImageView
android:src="#drawable/cat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:layout_above="#id/button_container"/>
</RelativeLayout>
</ScrollView>
The trick is that you set the ImageView to fill the screen but it has to be above the other layouts. This way you achieve everything you need.
Its simple matter of setting adjustViewBounds="true" and scaleType="fitCenter" in the XML file for the ImageView!
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/image"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
/>
Note: layout_width is set to match_parent
You are setting the ScaleType to ScaleType.FIT_XY. According to the javadocs, this will stretch the image to fit the whole area, changing the aspect ratio if necessary. That would explain the behavior you are seeing.
To get the behavior you want... FIT_CENTER, FIT_START, or FIT_END are close, but if the image is narrower than it is tall, it will not start to fill the width. You could look at how those are implemented though, and you should probably be able to figure out how to adjust it for your purpose.
ScaleType.CENTER_CROP will do what you want: stretch to full width, and scale the height accordingly. if the scaled height exceeds the screen limits, the image will be cropped.
Look there is a far easier solution to your problem:
ImageView imageView;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
imageView =(ImageView)findViewById(R.id.your_imageView);
Bitmap imageBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.your_image);
Point screenSize = new Point();
getWindowManager().getDefaultDisplay().getSize(screenSize);
Bitmap temp = Bitmap.createBitmap(screenSize.x, screenSize.x, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(temp);
canvas.drawBitmap(imageBitmap,null, new Rect(0,0,screenSize.x,screenSize.x), null);
imageView.setImageBitmap(temp);
}
You can use my StretchableImageView preserving the aspect ratio (by width or by height) depending on width and height of drawable:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class StretchableImageView extends ImageView{
public StretchableImageView(Context context) {
super(context);
}
public StretchableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public StretchableImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if(getDrawable()!=null){
if(getDrawable().getIntrinsicWidth()>=getDrawable().getIntrinsicHeight()){
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * getDrawable().getIntrinsicHeight()
/ getDrawable().getIntrinsicWidth();
setMeasuredDimension(width, height);
}else{
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = height * getDrawable().getIntrinsicWidth()
/ getDrawable().getIntrinsicHeight();
setMeasuredDimension(width, height);
}
}
}
}
For me the android:scaleType="centerCrop" did not resolve my problem. It actually expanded the image way more. So I tried with android:scaleType="fitXY" and It worked excellent.
This working fine as per my requirement
<ImageView
android:id="#+id/imgIssue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"/>