I'm trying to implement a similar kind of UI which yahoo weather app did. I am able to blur the background image with the listview based on this link. http://nicolaspomepuy.fr/?p=18. In the above URL the author is using Listview onScrollListerner. But I have to implement that effect using a scrollview.
Inside a scrollview I'll be having 3 pages with 3 views. On scrolling the first view I want the background image to be blurred. I wrote a custom scrollview which extends Scrollview to achieve the onScroll Changed functionality.
But couldn't able to change the alpha values of blured Image based on Scroll positions.
Here I'm attaching my sample code. Please help me to figure it out.
public class MainActivity extends Activity implements ScrollViewListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
mBlurredImage.setAlpha(alpha);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
screenWidth = displaymetrics.widthPixels;
empty.getLayoutParams().height = (int) (displaymetrics.heightPixels * 0.6);
// Try to find the blurred image
final File blurredImage = new File(getFilesDir() + BLURRED_IMG_PATH);
if (!blurredImage.exists()) {
new Thread(new Runnable() {
#Override
public void run() {
// No image found => let's generate it!
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.image, options);
Bitmap newImg = Blur.fastblur(MainActivity.this, image, 12);
ImageUtils.storeImage(newImg, blurredImage);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateView(screenWidth);
}
});
}
}).start();
} else {
// The image has been found. Let's update the view
updateView(screenWidth);
}
}
private void updateView(final int screenWidth) {
Bitmap bmpBlurred = BitmapFactory.decodeFile(getFilesDir() + BLURRED_IMG_PATH);
bmpBlurred = Bitmap.createScaledBitmap(bmpBlurred, screenWidth, (int) (bmpBlurred.getHeight()
* ((float) screenWidth) / (float) bmpBlurred.getWidth()), false);
mBlurredImage.setImageBitmap(bmpBlurred);
}
private void initUI() {
textView = (TextView) findViewById(R.id.textview);
empty = (LinearLayout) findViewById(R.id.empty);
scrollView = (ObservableScrollView) findViewById(R.id.customScrollView);
mBlurredImage = (ImageView) findViewById(R.id.blurred_image);
normalImage = (ImageView) findViewById(R.id.normal_image);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onScrollChanged(ObservableScrollView scrollView, int x, int y,
int oldx, int oldy) {
// TODO Auto-generated method stub
Log.i("Scrolling", "X from ["+oldx+"] to ["+x+"]");
Toast.makeText(this,"HI welcome ", Toast.LENGTH_SHORT).show();
alpha = (float) -textView.getTop() / (float) TOP_HEIGHT;
// // Apply a ceil
if (alpha > 1) {
alpha = 1;
}
}
}
public class ObservableScrollView extends ScrollView{
private ScrollViewListener scrollViewListener = null;
public ObservableScrollView(Context context) {
super(context);
}
public ObservableScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ObservableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setScrollViewListener(ScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
#Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
super.onScrollChanged(x, y, oldx, oldy);
if(scrollViewListener != null) {
scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
}
}
public interface ScrollViewListener {
void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy);
}
Here is the XML file
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.blureffect.TopCenterImageView
android:id="#+id/normal_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/image" />
<com.example.blureffect.TopCenterImageView
android:id="#+id/blurred_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alpha="0" />
<com.example.blureffect.ObservableScrollView
android:id="#+id/customScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
/>
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="It was a good track to bowl on. It had good bounce, the ball was turning sharply as well. We bowled in the right areas. When batsmen bat in partnerships the job is easy. That is the same case with bowlers. Ashwin and I have formed a good partnership. It has been a honour to play with Sachin paaji. I would like to dedicate my five-wicket haul to Sachin paaji. We were all motivated from yesterday and we want to enjoy this occasion." />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="It was a good track to bowl on. It had good bounce, the ball was turning sharply as well. We bowled in the right areas. When batsmen bat in partnerships the job is easy. That is the same case with bowlers. Ashwin and I have formed a good partnership. It has been a honour to play with Sachin paaji. I would like to dedicate my five-wicket haul to Sachin paaji. We were all motivated from yesterday and we want to enjoy this occasion." />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="It was a good track to bowl on. It had good bounce, the ball was turning sharply as well. We bowled in the right areas. When batsmen bat in partnerships the job is easy. That is the same case with bowlers. Ashwin and I have formed a good partnership. It has been a honour to play with Sachin paaji. I would like to dedicate my five-wicket haul to Sachin paaji. We were all motivated from yesterday and we want to enjoy this occasion." />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="It was a good track to bowl on. It had good bounce, the ball was turning sharply as well. We bowled in the right areas. When batsmen bat in partnerships the job is easy. That is the same case with bowlers. Ashwin and I have formed a good partnership. It has been a honour to play with Sachin paaji. I would like to dedicate my five-wicket haul to Sachin paaji. We were all motivated from yesterday and we want to enjoy this occasion." />
</LinearLayout>
</com.example.blureffect.ObservableScrollView>
</FrameLayout>
I had to implement something similar not a long time ago - in my case it was a vertical ScrollView that, when scrolled, would affect the blur of the background.
First of all, I implemented ObservableScrollView to expose the onScrollChanged() method and also to be able to set my own listener for it:
public void setScrollViewListener(ObservableScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
#Override
protected void onScrollChanged(int x, int y, int oldX, int oldY) {
super.onScrollChanged(x, y, oldX, oldY);
if(scrollViewListener != null) {
scrollViewListener.onScrollChanged(this, x, y, oldX, oldY);
}
}
Now, to achieve the blurring effect I basically change the alpha of the blurred background ImageView - shown in this snippet from my class which is responsible for both the ObservableScrollView and the ImageViews:
#Override
public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldX, int oldY) {
//...
// Blurring
float blurredImageAlpha = (float) y / SCROLL_VIEW_INITIAL_OFFSET;
if (blurredImageAlpha > 1.0) {
blurredImageAlpha = (float) 1.0;
}
imageBackgroundBlurred.setAlpha(blurredImageAlpha);
}
As you can see, I divide the y by a certain value simply not to have the the blur start straight away - this depends on what you exactly need.
As for my XML layout, it looks something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/aboutMainView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black"
android:padding="0dp" >
<ImageView
android:id="#+id/aboutImageBackground"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="#null"
android:scaleType="centerCrop"
android:src="#drawable/about_back_a" />
<ImageView
android:id="#+id/aboutImageBackgroundBlurred"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:alpha="0.0"
android:contentDescription="#null"
android:scaleType="centerCrop"
android:src="#drawable/about_back_b" />
<com.bronzelabs.maa.widgets.ObservableScrollView
android:id="#+id/aboutObservableScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="vertical" />
</RelativeLayout>
check out this sample project:
https://github.com/MoshDev/LikeYahooWeather
Related
i am continuously searching and trying to sort out a issue in custom view and Relative layout.
i found multiple solution but only few of solution are usefull,but they not fulfilling my requirement completely.
partial solution 1.
partial solution 2.
via these solution i can manage the height and width of my custom view, but i just want to align my custom view in center of parent RelativeLayout,
code which i am trying throw hit-and-run is below. ;)
JAVA CODE
public class MyActiveView extends View {
public Movie mMovie;
public long movieStart;
private int gifId;
public MyActiveView(Context context, AttributeSet attrs) {
super(context, attrs);
initializeView();
}
#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);
}
private void initializeView() {
InputStream is = getContext().getResources().openRawResource(R.raw.pj_logo1);
mMovie = Movie.decodeStream(is);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
super.onDraw(canvas);
long now = android.os.SystemClock.uptimeMillis();
if (movieStart == 0) {
movieStart = now;
}
if (mMovie != null) {
int relTime = (int) ((now - movieStart) % mMovie.duration());
mMovie.setTime(relTime);
mMovie.draw(canvas, getWidth() - mMovie.width(), getHeight() - mMovie.height());
this.invalidate();
}
}
public int getActiveResource() {
return this.gifId;
}
public void setActiveResource(int resId) {
this.gifId = resId;
initializeView();
}
}
XML CODE
<?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">
<ImageView
android:id="#+id/backsourceImagesplash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/bg_blur" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#color/colorTransparentWhite" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="256dp"
android:layout_centerVertical="true"
android:gravity="centre">
<pj.com.pjlib.activity_base.support_class.MyActiveView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
i want to set my custom active view layout in centre of its parent Relative Layout, but stuked in it. any help will be appreciated.
check the alignment of both image,i am trying for attribute android:layout_centerInParent="true", according to Relative layout support the "congrats image" should be in center, but it's not happening.
so i am thinking,i missed something in my custom view class but what is that, i don't know.
Change android:gravity="centre" with android:gravity="center" in Relative Layout. I think this will helpful to you.
I want to create buttons that look like in the picture. Inside the circle (which is transparent in the png) I want to place the profile picture of players. There should also be text on the blue bar.
I've got it working but it just seems way too complicated. I think it is easier to understand what I have done without giving code but if you need it I can add it. Here is the layout:
RelativeLayout
LinearLayout (horizontal orientation)
Empty view with weight 0.7
Profile Picture with weight 0.2
Empty view with weight 0.1
the overlay picture that I posted below
LinearLayout (horizontal orientation)
RelativeLayout with weight 0.7 (space where all the text can go)
empty view with weigh 0.3
By the way: to the right of the circle, the png isn't transparent but white!
This works well but there must be a better way! All these empty views just to align the picture to the right position is kind of ugly. And the fact that the overlay picture must go inbetween the profile picture and the text makes it even uglier.
I'd prefer to do it without a png as overlay but with simple shapes (so that it looks good on every screen) but I wouldn't know how to do that. Would you recommend that? And if yes, how could that be done?
Or do you have an idea how to improve the xml layout or how to do it otherwise.
Thanks very much
You can do it without any image:
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:weightSum="1.0">
<TextView
android:layout_weight="0.7"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="New Text"
android:id="#+id/textView"
android:background="#0073ff"/>
<ImageView
android:layout_weight="0.2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:background="#drawable/half_round_drawable"
android:src="#drawable/profile"/>
</LinearLayout>
</LinearLayout>
half_round_drawable:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="oval">
<corners android:radius="16dp" />
<solid android:color="#0073ff" />
</shape>
</item>
<item
android:bottom="0dp"
android:right="32dp"> <!-- radius *2 -->
<shape>
<solid android:color="#0073ff" />
</shape>
</item>
</layer-list>
To make the profile-image round you should use something like this:
How to create a circular ImageView in Android?
You can use a simple LinearLayout if you confine the background image to the profile area at the right side. You can define the content area in the image itself if you use a nine-patch drawable, as follows:
Extract the profile portion from your background image file.
Create a nine patch drawable from it, defining all the area as stretchable (left and top border lines), and the empty circle as the content area (right and bottom lines).
Since you should ideally have the image at the foreground layer to ensure that the photo isn't drawn outside of the circle, you can use a FrameLayout with a foreground drawable to contain your profile photo's ImageView. There would also need to be another dummy child view to work around a bug in FrameLayout that causes a single child with match_parent dimensions to be layout incorrectly.
This is how the layout should look like at the end:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#00f" />
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:foreground="#drawable/profile_bg">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/photo"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
Now I am ready to present my answer.
Portret:
Landscape:
Layout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:shape="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<!--This is the CustomView which include -->
<!--own attributes: -->
<!--circle_radius is the radius of image, -->
<!--content_padding is the padding,-->
<!--and background_color is the color of shape.-->
<CustomShape
android:layout_width="match_parent"
android:layout_height="wrap_content"
shape:circle_radius="40dp"
shape:content_padding="8dp"
shape:background_color="#FF983493">
<!--There must be two Views:-->
<!--TextView and ImageView and only in this order.-->
<!--Set-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--to bot of them, because in CustomShape it will be-->
<!--resized for you. There also don`t need to set -->
<!--any kind of margin or location attributes.-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txt"
android:padding="5dp"
android:textColor="#android:color/white"
android:text="sdsfkjsdkfhsdk flsdkfjkls asdfasd fklasdjl fkjasdklfjasd k "
android:background="#android:color/transparent"/>
<!--For RoundImage I use custom class which round the drawable,-->
<!--not a View. Look down.-->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/img"
android:src="#drawable/img"
android:scaleType="fitCenter"
android:background="#android:color/transparent" />
</CustomShape>
</RelativeLayout>
CustomShape class:
public class CustomShape extends RelativeLayout {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
int circleRadius; // image radius
int diameter; // image diameter
int contentPadding;
int semiPadding;
int rectRightSide;
int backgroundColor;
int viewWidth; // width of parent(CustomShape layout)
public CustomShape(Context context) {
super(context);
this.setWillNotDraw(false);
}
public CustomShape(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomShape, 0, 0);
try {
this.circleRadius = (int) ta.getDimension(R.styleable.CustomShape_circle_radius, 40);
this.contentPadding = (int) ta.getDimension(R.styleable.CustomShape_content_padding, 8);
this.backgroundColor = ta.getColor(R.styleable.CustomShape_background_color, 0);
this.semiPadding = contentPadding / 2;
this.diameter = circleRadius * 2;
} finally {
ta.recycle();
}
this.setWillNotDraw(false);
}
public CustomShape(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.setWillNotDraw(false);
}
#Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld) {
super.onSizeChanged(xNew, yNew, xOld, yOld);
viewWidth = xNew;
this.rectRightSide = viewWidth - circleRadius - (circleRadius / 2); // get position for image
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
ImageView img = (ImageView) this.getChildAt(1);
RelativeLayout.LayoutParams imgParams = new LayoutParams(diameter - contentPadding, diameter - contentPadding);
imgParams.leftMargin = rectRightSide - circleRadius + semiPadding;
imgParams.topMargin = semiPadding;
img.setLayoutParams(imgParams);
//Create custom RoundImage and set to image
try {
Drawable drawable = img.getDrawable();
Bitmap bm = ((BitmapDrawable) drawable).getBitmap();
RoundImage resultImage = new RoundImage(bm);
img.setImageDrawable(resultImage);
} catch (ClassCastException e) {
}
//Positioning and resizing TextView
View txt = this.getChildAt(0);
RelativeLayout.LayoutParams txtParams = new LayoutParams(rectRightSide - circleRadius - semiPadding, diameter - contentPadding);
txtParams.topMargin = semiPadding;
txtParams.leftMargin = semiPadding;
txt.setLayoutParams(txtParams);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
this.setMeasuredDimension(parentWidth, diameter); // set correct height
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(backgroundColor);
canvas.drawRect(0, 0, rectRightSide, diameter, paint);
//Draw circle
paint.setDither(true);
canvas.drawCircle(rectRightSide, circleRadius, circleRadius, paint);
}
}
Attr.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomShape">
<attr name="circle_radius" format="dimension" />
<attr name="content_padding" format="dimension" />
<attr name="background_color" format="color" />
</declare-styleable>
</resources>
RoundImage class:
public class RoundImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
Hope it will help you.
In the app Astrid Tasks, there is a button. When you press the button, a drop down menu comes up.
It's basically a spinner but in a drop-down-list form.
Does anyone know how to do something similar? Is this a widget I just don't see?
As the original author of this (I'm one of the primary Android developers for Astrid) I'd be happy to share how Astrid does it. I'll post the basics here, but you can find more details at our github repo (https://github.com/todoroo/astrid). The basic idea is to extend GreenDroid's QuickActionWidget as hanry suggests. The subclass looks something like:
public class MenuPopover extends QuickActionWidget {
protected DisplayMetrics metrics;
protected LinearLayout content;
public MenuPopover(Context context) {
super(context);
setContentView(R.layout.my_layout);
content = (LinearLayout) getContentView().findViewById(R.id.content);
metrics = context.getResources().getDisplayMetrics();
setFocusable(true);
setTouchable(true);
}
#Override
protected void populateQuickActions(List<QuickAction> quickActions) {
// Do nothing
}
#Override
protected void onMeasureAndLayout(Rect anchorRect, View contentView) {
contentView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
contentView.measure(MeasureSpec.makeMeasureSpec(getScreenWidth(), MeasureSpec.EXACTLY),
ViewGroup.LayoutParams.WRAP_CONTENT);
int rootHeight = contentView.getMeasuredHeight();
int offsetY = getArrowOffsetY();
int dyTop = anchorRect.top;
int dyBottom = getScreenHeight() - anchorRect.bottom;
boolean onTop = (dyTop > dyBottom);
int popupY = (onTop) ? anchorRect.top - rootHeight + offsetY : anchorRect.bottom - offsetY;
setWidgetSpecs(popupY, onTop);
}
}
The layout file my_layout.xml is pretty simple:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dip">
<LinearLayout
android:id="#+id/content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/gdi_arrow_up"
android:orientation="vertical"/>
<ImageView
android:id="#+id/gdi_arrow_up"
android:layout_width="27dip"
android:layout_height="27dip"
android:layout_marginLeft="-10dip"
android:scaleType="fitCenter"
android:layout_marginBottom="-8dip"
android:src="?attr/asListArrowUp" />
<ImageView
android:id="#+id/gdi_arrow_down"
android:layout_width="27dip"
android:layout_height="27dip"
android:scaleType="fitCenter"
android:layout_marginBottom="-8dip"
android:layout_below="#android:id/list"/>
</RelativeLayout>
</FrameLayout>
Then, you can just add a simple helper method to the popover class to add views (i.e. rows, with optional listeners) to the main body of the popover:
public void addViewToContent(View v, OnClickListener listener) {
content.addView(v);
if (listener != null) {
v.setOnClickListener(listener);
}
}
After creating an instance of the popup, you can show it by calling
menuPopover.show(anchorView);
This is a somewhat simplified version -- in practice, we attach some addition information, listeners, etc. to those views to make them actually do things when clicked. If you want, you can check out the full code at https://github.com/todoroo/astrid -- the class is com.todoroo.astrid.ui.MainMenuPopover.
Thanks for using Astrid!
After trying out the Gallery and Horizontal Scroll View, I found that the View Pager does what I need but with one minor thing missing. Can the View Pager have multiple views per page?
I know that View Pager shows only 1 view/page per swipe. I was wondering if I can limit my views width so my 2nd view following it will show?
For example: I have 3 views and I want the screen to show view 1 and part of view 2 so the user knows there is more content so they can swipe to view 2.
|view 1|view 2|view 3|
|screen |
I discovered that a perhaps even simpler solution through specifying a negative margin for the ViewPager. I've created the MultiViewPager project on GitHub, which you may want to take a look at:
https://github.com/Pixplicity/MultiViewPager
Although MultiViewPager expects a child view for specifying the dimension, the principle revolves around setting the page margin:
ViewPager.setPageMargin(
getResources().getDimensionPixelOffset(R.dimen.viewpager_margin));
I then specified this dimension in my dimens.xml:
<dimen name="viewpager_margin">-64dp</dimen>
To compensate for overlapping pages, each page's content view has the opposite margin:
android:layout_marginLeft="#dimen/viewpager_margin_fix"
android:layout_marginRight="#dimen/viewpager_margin_fix"
Again in dimens.xml:
<dimen name="viewpager_margin_fix">32dp</dimen>
(Note that the viewpager_margin_fix dimension is half that of the absolute viewpager_margin dimension.)
We implemented this in the Dutch newspaper app De Telegraaf Krant:
Mark Murphy has an interesting blog post addressing precisely this problem. Although I ended up using my own solution in this thread, it's worthwhile looking at Dave Smith's code, which Mark references in the blog post:
https://gist.github.com/8cbe094bb7a783e37ad1/
Warning! Before you take this approach, beware of some very serious issues with this approach, mentioned both at the end of this post and in the comments below.
You'll end up with this:
It effectively works by wrapping a ViewPager into a subclass of FrameLayout, setting it to a specific size, and calling setClipChildren(false). This inhibits Android from clipping the views that exceed beyond the boundaries of the ViewPager, and visually accomplishes what you want.
In XML, it's very simple:
<com.example.pagercontainer.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#CCC">
<android.support.v4.view.ViewPager
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal" />
</com.example.pagercontainer.PagerContainer>
Add in a little code for handling touch events from outside of the ViewPager and invalidating the display when scrolling, and you're done.
That being said, and while this works great in general, I did notice that there is an edge-case that isn't solved with this fairly simple construction: when calling setCurrentPage() on the ViewPager. The only way I could find to resolve this was by subclassing ViewPager itself and having its invalidate() function also invalidate the PagerContainer.
It is possible to show more than one page on the same screen.
One of the ways is by overriding the getPageWidth() method in the PAgerAdapter. getPageWidth() returns a float number between 0 and 1 indicating how much width of the Viewpager should the page occupy. By default it is set to 1. So, you can change this to the width you wish.
You can read more about this here & github project.
This is how I got it:
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="center"
android:layout_marginBottom="8dp"
android:clipToPadding="false"
android:gravity="center"
android:paddingLeft="36dp"
android:paddingRight="36dp"/>
and in activity,i use this :
markPager.setPageMargin(64);
hope it helps!
I had the same problem with the only difference that i needed to show 3 pages at once (previous, current and next pages). After a really long research for the best solution i think i found it.
The solution is a mix of few of the answers here:
As #Paul Lammertsma's answer pointed out - Dave Smith's code in Mark Murphy's blog is the basis for the solution. The only problem for me was that the ViewPager was only on the top part of the screen due to the size they give it in the xml file:
android:layout_width="150dp"
android:layout_height="100dp"
Which wasn't good for my purpose since i was looking for something that will spread all over the screen. So i changed it to wrap the content as you can see here:
<com.example.nutrino_assignment.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CCC">
<android.support.v4.view.ViewPager
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</com.example.nutrino_assignment.PagerContainer>
Now I lost all the effect of what the tutorial was trying to do. Using #andro's answer i was able to show more then 1 page at a time: exactly 2! The current and the next.
Did so by overriding as follow:
#Override
public float getPageWidth(int position) {
return(0.9f);
}
That was almost what i needed... (even though i think its enough for what you were asking), but for others who might need something like what i was needed:
For the last part of the solution i used the idea in this answer, again by #Paul Lammertsma.
In Dave Smith's code you will find in the onCreate method this line:
//A little space between pages
pager.setPageMargin(15);
which i replaced with:
//A little space between pages
pager.setPageMargin(-64);
now on the first page looks:
|view 1|view 2|view 3|
|screen |
while on the 2nd it looks like:
|view 1|view 2|view 3|
|screen |
Hope it will help someone! I wasted like 2 days on it...
Good luck.
viewPager.setPageMargin(-18);// adjust accordingly ,-means less gap
in imageadapter
private class ImagePagerAdapter2 extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.add1,
R.drawable.add3,
R.drawable.add4,
R.drawable.add2,
};
#Override
public float getPageWidth(int position) {
return .3f;
}
adjust return value...lesser means more image......0.3 means atleast 3 images at a time.
LayoutParams lp = new LayoutParams(width,height);
viewpager.setLayoutParams(lp);
In xml file using this code(Main Activity)
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="130dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:orientation="vertical"
android:weightSum="1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="130dp">
<com.wonderla.wonderla.muthootpathanamthitta.activity_muthootpathanm.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="100dip"
android:layout_height="100dip"/>
</com.wonderla.wonderla.muthootpathanamthitta.activity_muthootpathanm.PagerContainer>
</RelativeLayout>
</LinearLayout>
Main activity xml file add this code
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="130dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:orientation="vertical"
android:weightSum="1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="130dp">
<com.wonderla.wonderla.muthootpathanamthitta.activity_muthootpathanm.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="100dip"
android:layout_height="100dip"/>
</com.wonderla.wonderla.muthootpathanamthitta.activity_muthootpathanm.PagerContainer>
</RelativeLayout>
</LinearLayout>
Main Activity code
public class MainActivity extends Activity{
final Integer[] XMEN2= {R.mipmap.bookticket,R.mipmap.safty,R.mipmap.privacy};
private ArrayList<Integer> XMENArray2 = new ArrayList<Integer>();
PagerContainer mContainer;
int currentPage2 = 0;
private static int NUM_PAGES2 = 0;
ViewPager mPager2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
initData2();}
private void initViews() {
mPager2 = (ViewPager)findViewById(R.id.viewpager);
mContainer = (PagerContainer)findViewById(R.id.pager_container);
mPager2.setOffscreenPageLimit(5);
mPager2.setPageMargin(15);
mPager2.setClipChildren(false);
}
private void initData2() {
for(int i=0;i<XMEN2.length;i++)
XMENArray2.add(XMEN2[i]);
mPager2.setAdapter(new Sliding_Adaptertwo(getActivity(),XMENArray2));
NUM_PAGES2 =XMEN2.length;
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage2 == NUM_PAGES2) {
currentPage2= 0;
}mPager2.setCurrentItem(currentPage2++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);
}
}
Pager View pagercontainer class
import android.content.Context;
import android.graphics.Point;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
public class PagerContainer extends FrameLayout implements ViewPager.OnPageChangeListener {
private ViewPager mPager;
boolean mNeedsRedraw = false;
public PagerContainer(Context context) {
super(context);
init();
}
public PagerContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagerContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
//Disable clipping of children so non-selected pages are visible
setClipChildren(false);
//Child clipping doesn't work with hardware acceleration in Android 3.x/4.x
//You need to set this value here if using hardware acceleration in an
// application targeted at these releases.
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
try {
mPager = (ViewPager) getChildAt(0);
mPager.setOnPageChangeListener(this);
} catch (Exception e) {
throw new IllegalStateException("The root child of PagerContainer must be a ViewPager");
}
}
public ViewPager getViewPager() {
return mPager;
}
private Point mCenter = new Point();
private Point mInitialTouch = new Point();
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCenter.x = w / 2;
mCenter.y = h / 2;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
//We capture any touches not already handled by the ViewPager
// to implement scrolling from a touch outside the pager bounds.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialTouch.x = (int)ev.getX();
mInitialTouch.y = (int)ev.getY();
default:
ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y - mInitialTouch.y);
break;
}
return mPager.dispatchTouchEvent(ev);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Force the container to redraw on scrolling.
//Without this the outer pages render initially and then stay static
if (mNeedsRedraw) invalidate();
}
#Override
public void onPageSelected(int position) { }
#Override
public void onPageScrollStateChanged(int state) {
mNeedsRedraw = (state != ViewPager.SCROLL_STATE_IDLE);
}
}
and its Adapter
public class Sliding_Adaptertwo extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
public Sliding_Adaptertwo(Context context, ArrayList<Integer> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.sliding_layout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
xml file of adapter class
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/image"
android:layout_width="90dp"
android:layout_height="90dp"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/ad1"
/>
</FrameLayout>
it works fine
In default handle button in android SlidingDrawer in the centre of the drawer. Is it possible to change that position to left or right..? If it possible how can I do that, android:gravity="left" is not work in the button.
Put your handle in a RelativeLayout, and set android:layout_alignParentRight="true" on the handle.
For example like this:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<SlidingDrawer android:id="#+id/drawer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:handle="#+id/handle"
android:content="#+id/content">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/handle">
<ImageView android:src="#drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
<LinearLayout
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#aaaa00" android:id="#+id/content">
<ImageView android:src="#drawable/icon"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">
</ImageView>
</LinearLayout>
</SlidingDrawer>
</FrameLayout>
The problem I had with HenrikS answer was that in my case I had some views behind the relative layout and when I tried to click them I realized that the relative layout was intercepting those clicks because the width was set to fill_parent.
To workaround this I modified the layout of the handler view (the ImageView) in my case to the left, hope it is helpful.
public class CustomSlidingDrawer extends SlidingDrawer {
public CustomSlidingDrawer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CustomSlidingDrawer(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
final int height = b - t;
ImageView handle = (ImageView) getHandle();
int childLeft = 0;
int childWidth = handle.getWidth();
int topOffset = 0;
int bottomOffest = 0;
int childHeight = handle.getHeight();
int childTop = this.isOpened()?topOffset:height - childHeight + bottomOffest;
handle.layout(childLeft, childTop , childLeft + childWidth, childTop+childHeight);
}
}
The idea is simple: set the handle's padding to the correct value depending on the alignment you want.
In the example below, I derive a class from SlidingDrawer and override onLayout as follows. My sliding drawer is at the bottom of the screen, and I want the handle to be left-aligned rather than center-aligned.
public class ToolDrawer extends SlidingDrawer {
private int m_handleWidth = 0; // original handle width
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
if (x <= m_handleWidth) {
return super.onTouchEvent(event);
}
return false;
}
protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (changed) {
ImageView iv = (ImageView) getHandle();
iv.setPadding(0, 0, getWidth() - iv.getWidth(), 0);
if (m_handleWidth == 0) {
m_handleWidth = iv.getWidth();
}
}
}
}
It's as simple as that.
I tried android:paddingBottom="300dp" for the ImageView and it works fine, also with left, right and top.
But you have to set the padding from the middle-position, so bottom="300dp" means the handle move up 300 from the middle
A simpler solution for left-aligned handle:
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
final View handle = getHandle();
handle.layout(0, handle.getTop(), handle.getWidth(), handle.getBottom());
}
I have researched this problem for 2 days and I realized that you need to use another library. Because, when you use RelativeLayout or LinearLayout, you're just get fill_parent screen and of course it will be affected by touching ( although you don't touch on icon ).
So, I use SlidingTray from Sileria library ( ver 3.5 ) http://aniqroid.sileria.com/doc/api/
Then like this
I found the solution for garibay
You just need to set android:clickable="true" on content layout of sliding drawer.