Get first visible view inside of NestedScrollView - android

I have a next problem.
I'm trying to get first visible item inside of NestedScrollView. Actually, first and only view inside is LinearLayout (because scroll view can hold only one direct child), but I'm trying to get first visible item inside it. I was searching a lot but without success.
With this approach, I want to avoid using RecyclerView inside another RecyclerView. I found it is a bad practice.
P.S. I don't want to use ListView or RecyclerView
Thanks in advance

Okay, I found a solution:
final Rect scrollBounds = new Rect();
questionAndAnswerScroll.getHitRect(scrollBounds);
questionAndAnswerScroll.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
#Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
for (int i = 0; i < questionAndAnswerHolder.getChildCount(); i++) {
View childView = questionAndAnswerHolder.getChildAt(i);
if (childView != null) {
if (childView.getLocalVisibleRect(scrollBounds)) {
//Here is the position of first visible view
positionToScroll = i;
break;
}
}
}
}
});

for this layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/ly"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="text_1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="text_2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="text_3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="text_4" />
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="text_5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="text_6" />
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="text_7" />
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="text_8" />
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="text_9" />
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="text_10" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
and use this code
public class MainActivity extends AppCompatActivity {
NestedScrollView nestedScrollView;
LinearLayout linearLayout;
ArrayList<Integer> childrenY = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find view
nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);
linearLayout = (LinearLayout) nestedScrollView.getChildAt(0);
//get Y Children and save
for (int i = 0; i < linearLayout.getChildCount(); i++) {
int childrenY = 0;
for (int j = 0; j < i; j++) {
TextView tv = (TextView) linearLayout.getChildAt(j);
Log.i("--------", tv.getText().toString());
childrenY += tv.getLayoutParams().height;
}
this.childrenY.add(childrenY);
}
//add Scroll Change Listener
nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
#Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
for (int i = 0; i < childrenY.size(); i++) {
if (scrollY < childrenY.get(i)) {
Log.i("++++++++++", ((TextView) linearLayout.getChildAt(i-1)).getText().toString());
return;
}
}
}
});
}
}

If you want to find the first visible item inside inner LinearLayout of NestedScrollView, you may try this:
if(nsv.getChildCount() > 0) {
ViewGroup vg = (ViewGroup) nsv.getChildAt(0);
for (int i = 0; i < vg.getChildCount(); i++) {
if(vg.getChildAt(i).getVisibility()==View.VISIBLE)
return vg.getChildAt(i);
}
}
return null;
Where nsv is your NestedScrollView.

Related

Cardview doesn't have any affect on items

I'm trying to make my RecyclerView prettier, so I added a CardView. However, I don't see any changes when I ran the app, the UI looks like as if there's no CardView at all - there is not separation between the items. Can you please suggest what's wrong with my code here?
This is my list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="6dp">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.AppCompatTextView
android:id="#+id/link_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="1dp"
android:layout_marginBottom="10dp"
android:layout_marginStart="10dp"
android:text="#string/title_place_holder"/>
<LinearLayout
android:layout_below="#id/link_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<android.support.v7.widget.AppCompatImageView
android:id="#+id/link_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_gravity="center"
app:srcCompat="#drawable/ic_launcher_background"/>
<android.support.v7.widget.AppCompatTextView
android:id="#+id/link_summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="15sp"
android:padding="1dp"
android:text="#string/summary_place_holder"/>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
This is how I initialize my RecylerView:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
mAdapter = new PostsAdapter(mPostList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mAdapter);
preparePostData();
}
This can be achieved with a 1 line change in xml applied to the CardView element applying a margin.
android:layout_margin"#dimen/default_margin"
With your code:
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="6dp"
android:layout_margin"#dimen/default_margin">
And in the dimens resources file
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<dimen name="default_margin">10dp</dimen>
</resources>
I have made changes in your code, please try below code
in place on
card_view:cardCornerRadius="4dp"
card_view:cardElevation="6dp"
I've changed to below
app:cardCornerRadius="4dp"
app:cardElevation="6dp"
app:cardUseCompatPadding="true"
Just replace below layout code
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com /apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:cardCornerRadius="4dp"
app:cardElevation="6dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:id="#+id/link_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="1dp"
android:layout_marginBottom="10dp"
android:layout_marginStart="10dp"
android:text="#string/title_place_holder"/>
<LinearLayout
android:layout_below="#id/link_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<android.support.v7.widget.AppCompatImageView
android:id="#+id/link_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_gravity="center"
app:srcCompat="#drawable/ic_launcher_background"/>
<android.support.v7.widget.AppCompatTextView
android:id="#+id/link_summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="15sp"
android:padding="1dp"
android:text="#string/summary_place_holder"/>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
You need item decoration in RecyclerView with equal spacing around item!
Note : make sure yourRecyclerView background is different that item background
EqualSpacingItemDecoration.java
import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class EqualSpacingItemDecoration extends RecyclerView.ItemDecoration {
private final int top;
private final int left;
private final int bottom;
private final int right;
private int displayMode;
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
public static final int GRID = 2;
public EqualSpacingItemDecoration(int top, int left, int bottom, int right) {
this(top, left, bottom, right, -1);
}
public EqualSpacingItemDecoration(int top, int left, int bottom, int right, int displayMode) {
this.top = top;
this.left = left;
this.bottom = bottom;
this.right = right;
this.displayMode = displayMode;
}
#Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildViewHolder(view).getAdapterPosition();
int itemCount = state.getItemCount();
RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
setSpacingForDirection(outRect, layoutManager, position, itemCount);
}
private void setSpacingForDirection(Rect outRect,
RecyclerView.LayoutManager layoutManager,
int position,
int itemCount) {
// Resolve display mode automatically
if (displayMode == -1) {
displayMode = resolveDisplayMode(layoutManager);
}
switch (displayMode) {
case HORIZONTAL:
outRect.left = left;
outRect.right = position == itemCount - 1 ? right : 0;
outRect.top = top;
outRect.bottom = bottom;
break;
case VERTICAL:
outRect.left = left;
outRect.right = right;
outRect.top = top;
outRect.bottom = position == itemCount - 1 ? bottom : 0;
break;
case GRID:
if (layoutManager instanceof GridLayoutManager) {
GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
int cols = gridLayoutManager.getSpanCount();
int rows = itemCount / cols;
outRect.left = left;
outRect.right = position % cols == cols - 1 ? right : 0;
outRect.top = top;
outRect.bottom = position / cols == rows - 1 ? bottom : 0;
}
break;
}
}
private int resolveDisplayMode(RecyclerView.LayoutManager layoutManager) {
if (layoutManager instanceof GridLayoutManager) return GRID;
if (layoutManager.canScrollHorizontally()) return HORIZONTAL;
return VERTICAL;
}
#Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
}
}
Use like :
...
mRecyclerView..addItemDecoration(new EqualSpacingItemDecoration(12,12,12,12,1))
...
Just simply use app:cardUseCompatPadding="true" in CardView tag.
Try this in your manifest application tag.
android:hardwareAccelerated="true"

How to get First Visible child item of android Horizontal scrollview on scrollChange event

I need to find the first visible child item of android Horizontal scrollview on scrollChange event. I have followed this link How to get First Visible child item of android scrollview on scrollChange event
but couldn't find what rowView is.
horizontalScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
int scrollPos = horizontalScrollView1.getScrollX();
Log.e("scroll x:", scrollPos + "");
}
});
layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="15dp"
android:fillViewport="true"
android:scrollbars="none">
<RelativeLayout
android:id="#+id/layLandmarks"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<View
android:id="#+id/viewWhite"
android:layout_width="match_parent"
android:layout_height="10dp"
android:layout_centerInParent="true"
android:background="#color/white" />
</RelativeLayout>
</HorizontalScrollView>
</RelativeLayout>
Class file:
ImageView iv;
RelativeLayout layLandmarks = (RelativeLayout) findViewById(R.id.layLandmarks);
FrameLayout.LayoutParams lp1 = new FrameLayout.LayoutParams(2000, FrameLayout.LayoutParams.WRAP_CONTENT);
layLandmarks.setLayoutParams(lp1);
JSONObject landmarks = jsonObject1.getString("landmarks");
JSONArray jsonArray1 = new JSONArray(landmarks);
for (int j = 0; j < jsonArray1.length(); j++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(0);
landmarkId = jsonObject2.getString("id");
landmarkName = jsonObject2.getString("title");
landmarkDesc = jsonObject2.getString("description");
latitude = jsonObject2.getDouble("latitude");
longitude = jsonObject2.getDouble("longitude");
video_time = jsonObject2.getString("video_time_in_sec");
// Log.e("video_time_in_sec", video_time);
landmarkIcon = jsonObject2.getString("image");
iv = new ImageView(VideoPreviewWithRecycler.this);
iv.setId(i);
Picasso
.with(VideoPreviewWithRecycler.this)
.load(landmarkIcon)
.resize(40, 45)
.into(iv);
params = new RelativeLayout.LayoutParams(40, 45);
params.topMargin = 0;
params.leftMargin = Integer.parseInt(video_time);
params.addRule(RelativeLayout.RIGHT_OF, 0);
layLandmarks.addView(iv, params);
}
Update:
horizontalScrollView1.setOnScrollChangeListener(new View.OnScrollChangeListener() {
#Override
public void onScrollChange(View v, final int scrollX, int scrollY, final int oldScrollX, int oldScrollY) {
horizontalScrollView1.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int firstVisibleItemIndex= getFirstVisibleItem1(horizontalScrollView1);
Log.e("firstVisibleItemIndex >>",firstVisibleItemIndex+"");
}
});
}
});
private int getFirstVisibleItem1(HorizontalScrollView scrollView) {
ViewGroup viewGroup = (ViewGroup) scrollView.getChildAt(0); // cast to ViewGroup here because I think we only need to getFirstVisibleItem if ScrollView have multiple items
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View view = viewGroup.getChildAt(i);
if (view.getX() + view.getWidth() >= scrollView.getScrollX()) {
return i; // if you want to receive the position, return i here
}
}
return 0;
}
I think it may help
private View getFirstVisibleItem(HorizontalScrollView scrollView) {
ViewGroup viewGroup = (ViewGroup) scrollView.getChildAt(0); // cast to ViewGroup here because I think we only need to getFirstVisibleItem if ScrollView have multiple items
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View view = viewGroup.getChildAt(i);
if (view.getX() + view.getWidth() >= scrollView.getScrollX()) {
return view; // if you want to receive the position, return turn i here
}
}
return null;
}
The idea is check each view x position and scroll x value
I implemented some basic scrolling animation in my app. I used this piece of code and it is working perfectly fine.
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
switch (newState) {
case RecyclerView.SCROLL_STATE_IDLE:
case RecyclerView.SCROLL_STATE_DRAGGING:
case RecyclerView.SCROLL_STATE_SETTLING:
currentItemPosition=linearLayoutManager.findFirstCompletelyVisibleItemPosition();
}
}
my requirement was to find the position during settling of scroll ,you can try the same during SCROLL_STATE_IDLE
There are few methods but I prefer only one.
All Views have "boolean View.getGlobalVisibleRect(..)" ( https://developer.android.com/reference/android/view/View.html#getGlobalVisibleRect(android.graphics.Rect) ) method that returns FALSE if the View is completly hidden by its parent.
So all HorizontalScrollView's child has that HScrollView as its parent and if that method returns FALSE it means that View is not visible. The first child returning TRUE is the first visible child inside that HScrollView.
You can use Linearlayout Instead of RelaytiveLayout as a child of HorizontalScrollView. Like this:
<?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="wrap_content">
<HorizontalScrollView
android:id="#+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none">
<LinearLayout
android:id="#+id/layLandmarks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp" />
</HorizontalScrollView>
</RelativeLayout>
Note: You can also use custom layout to inflate in views in LinearLayout for more performance in case of nested Layouts. (I used a TextView not Custom Layout here)
In your activity use something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final HorizontalScrollView horizontalScrollView = findViewById(R.id.horizontalScrollView);
TextView iv;
final LinearLayout layLandmarks = findViewById(R.id.layLandmarks);
for (int j = 0; j < 10; j++) {
iv = new TextView(this);
iv.setId(j);
iv.setText("TEXT " + j);
iv.setPadding(20, 20, 20, 20);
layLandmarks.addView(iv);
}
horizontalScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
int firstVisibleItemIndex = getFirstVisibleItem(layLandmarks, horizontalScrollView);
Log.e("ItemIndex >>", firstVisibleItemIndex + "");
}
});
}
Now Use the code below. It modified version of #Phan Van Linh Answer.
private int getFirstVisibleItem(LinearLayout linearLayout, HorizontalScrollView horizontalScrollView) {
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View view = linearLayout.getChildAt(i);
if (view.getX() + view.getWidth() >= horizontalScrollView.getScrollX()) {
return i; // if you want to receive the position, return i here
}
}
return 0;
}
I Hope this will solve your problem. :)

First image appearing small in size and on top left corner in a viewpager when rotate the device

Hi in my application i am using the Viewpager with PagerAdapter. it contains n number of images. but when i rotate the device when viewpager is on first image then the image shift to top left corner and appears very small. please have a look in the attached image.
code which i am using
public class CustomViewPager extends ViewPager {
private final long SWITCH_TIME_INTERVAL = 5000;
public CustomViewPager(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomViewPager(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
postDelayed(mSwither, SWITCH_TIME_INTERVAL);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height)
height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
/**
* this Runnable is use for automatically switching the view pager item.
* #author
*/
private Runnable mSwither = new Runnable() {
#Override
public void run() {
if( CustomViewPager.this.getAdapter() != null )
{
int count = CustomViewPager.this.getCurrentItem();
if( count == (CustomViewPager.this.getAdapter().getCount() - 1) )
{
count = 0;
}else
{
count++;
}
//Log.d(this.getClass().getName(), "Curent Page " + count + "");
CustomViewPager.this.setCurrentItem(count, true);
}
CustomViewPager.this.postDelayed(this, SWITCH_TIME_INTERVAL);
}
};
#Override
public boolean onTouchEvent(MotionEvent arg0) {
switch (arg0.getAction()) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP :
postDelayed(mSwither, SWITCH_TIME_INTERVAL);
break;
default:
removeCallbacks(mSwither);
break;
}
return super.onTouchEvent(arg0);
} }
//PagerAdapter onInstantiateItem code..
#Override
public Object instantiateItem(ViewGroup container, final int position) {
mImageFetcher.setLoadingImage(R.drawable.placeholder_tabportrait);
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.test_fragment1, container, false);
description = (TextView) itemView.findViewById(R.id.description);
title = (TextView) itemView.findViewById(R.id.car_title);
published = (TextView) itemView.findViewById(R.id.date_data);
author = (TextView) itemView.findViewById(R.id.author);
jumbo_tron_image = (ImageView) itemView.findViewById(R.id.jumbo_imgae);
TrayItem trayItem = getData(position);
if (null != trayItem) {
if (trayItem.getType() != null) {
if (trayItem.getImages() != null) {
mImageFetcher.loadImage(trayItem.getImages().getWidget(),
jumbo_tron_image);
}
return itemView;
}
//xml code.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="500dp"
android:background="#color/white">
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical"
>
<ImageView
android:id="#+id/jumbo_imgae"
android:layout_width="match_parent"
android:scaleType="fitXY"
android:layout_height="300dp"
/>
</FrameLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="#dimen/container_height"
android:layout_below="#+id/main_container">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
android:id="#+id/linearLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_alignParentLeft="true"
android:textStyle="bold"
android:layout_weight="0.5"
android:textColor="#color/black"
android:id="#+id/car_title"
android:maxLines="2"
android:ellipsize="end"
android:textSize="20sp"
android:text=" "/>
<ImageView
android:id="#+id/iv_add_test1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:paddingTop="10dp"
android:src="#drawable/add_icon"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/car_title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout2"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/linearLayout3"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:id="#+id/date_data"
android:layout_width="90dp"
android:layout_height="18dp"
android:text=""
android:textSize="13sp"
android:layout_gravity="left"
android:gravity="center"
android:textColor="#color/white"
android:background="#drawable/date_bg"/>
<TextView
android:id="#+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="15sp"
android:layout_marginLeft="10dp"
android:textColor="#color/black"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout> </RelativeLayout>

click event of button not getting raised

I am trying to make something like customised quick badge with some buttons on it. I have successfully desgined it but when i am clicking on those buttons it does nothing. Can someone tell me where am i going wrong.
demo_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/likemenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="30dp"
android:text="Button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" >
</TextView>
<Button
android:id="#+id/likequickaction"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="30dp"
android:text="Button" />
</LinearLayout>
popup_grid_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<FrameLayout
android:id="#+id/header2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10.0dip"
android:background="#drawable/quickaction_top_frame" />
<ImageView
android:id="#+id/arrow_up"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="#drawable/quickaction_arrow_up" />
<HorizontalScrollView
android:id="#+id/scroll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/header2"
android:background="#drawable/quickaction_slider_background"
android:fadingEdgeLength="0.0dip"
android:paddingLeft="1.0dip"
android:scrollbars="none" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="#drawable/quickaction_slider_grip_left" />
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/api_buttons" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="#drawable/quickaction_slider_grip_right" />
</LinearLayout>
</HorizontalScrollView>
<FrameLayout
android:id="#+id/footer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/scroll"
android:background="#drawable/quickaction_bottom_frame" />
</RelativeLayout>
api_buttons.xml
<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/horizontalScrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/quickaction_slider_background" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/one"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="One" />
<Button
android:id="#+id/two"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="Two" />
<Button
android:id="#+id/three"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="Three" />
<Button
android:id="#+id/four"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="Four" />
<Button
android:id="#+id/five"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="Five" />
<Button
android:id="#+id/six"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="Six" />
</TableRow>
</HorizontalScrollView>
BetterPopupWindow.java
public class BetterPopupWindow {
protected final View anchor;
private final PopupWindow window;
private View root;
private Drawable background = null;
private final WindowManager windowManager;
public BetterPopupWindow(View anchor) {
this.anchor = anchor;
this.window = new PopupWindow(anchor.getContext());
// when a touch even happens outside of the window
// make the window go away
this.window.setTouchInterceptor(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
BetterPopupWindow.this.window.dismiss();
return true;
}
return false;
}
});
this.windowManager = (WindowManager) this.anchor.getContext()
.getSystemService(Context.WINDOW_SERVICE);
onCreate();
}
protected void onCreate() {
}
protected void onShow() {
}
private void preShow() {
if (this.root == null) {
throw new IllegalStateException(
"setContentView was not called with a view to display.");
}
onShow();
if (this.background == null) {
this.window.setBackgroundDrawable(new BitmapDrawable());
} else {
this.window.setBackgroundDrawable(this.background);
}
this.window.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
this.window.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
this.window.setTouchable(true);
this.window.setFocusable(true);
this.window.setOutsideTouchable(true);
this.window.setContentView(this.root);
}
public void setBackgroundDrawable(Drawable background) {
this.background = background;
}
public void setContentView(View root) {
this.root = root;
this.window.setContentView(root);
}
public void setContentView(int layoutResID) {
LayoutInflater inflator = (LayoutInflater) this.anchor.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.setContentView(inflator.inflate(layoutResID, null));
}
public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
this.window.setOnDismissListener(listener);
}
public void showLikePopDownMenu() {
this.showLikePopDownMenu(0, 0);
}
public void showLikePopDownMenu(int xOffset, int yOffset) {
this.preShow();
this.window.setAnimationStyle(R.style.Animations_PopDownMenu);
this.window.showAsDropDown(this.anchor, xOffset, yOffset);
}
public void showLikeQuickAction() {
this.showLikeQuickAction(0, 0);
}
public void showLikeQuickAction(int xOffset, int yOffset) {
this.preShow();
this.window.setAnimationStyle(R.style.Animations_GrowFromBottom);
int[] location = new int[2];
this.anchor.getLocationOnScreen(location);
Rect anchorRect = new Rect(location[0], location[1], location[0]
+ this.anchor.getWidth(), location[1] + this.anchor.getHeight());
this.root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int rootWidth = this.root.getMeasuredWidth();
int rootHeight = this.root.getMeasuredHeight();
int screenWidth = this.windowManager.getDefaultDisplay().getWidth();
int screenHeight = this.windowManager.getDefaultDisplay().getHeight();
int xPos = ((screenWidth - rootWidth) / 2) + xOffset;
int yPos = anchorRect.top - rootHeight + yOffset;
// display on bottom
if (rootHeight > anchorRect.top) {
yPos = anchorRect.bottom + yOffset;
this.window.setAnimationStyle(R.style.Animations_GrowFromTop);
}
this.window.showAtLocation(this.anchor, Gravity.NO_GRAVITY, xPos, yPos);
}
public void dismiss() {
this.window.dismiss();
}
}
LikeQuickActionDemo.java
public class LikeQuickActionsDemo extends Activity {
private Button likemenuButton;
private Button likequickactionButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.demo_layout);
this.likemenuButton = (Button) this.findViewById(R.id.likemenu);
this.likemenuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DemoPopupWindow dw = new DemoPopupWindow(v);
dw.showLikePopDownMenu();
}
});
this.likequickactionButton = (Button) this
.findViewById(R.id.likequickaction);
this.likequickactionButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
DemoPopupWindow dw = new DemoPopupWindow(v);
dw.showLikePopDownMenu(0, 200);
}
});
}
private static class DemoPopupWindow extends BetterPopupWindow implements
OnClickListener {
public DemoPopupWindow(View anchor) {
super(anchor);
}
protected void onCreate() {
// inflate layout
LayoutInflater inflater = (LayoutInflater) this.anchor.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup root = (ViewGroup) inflater.inflate(
R.layout.popup_grid_layout, null);
// setup button events
for (int i = 0, icount = root.getChildCount(); i < icount; i++) {
View v = root.getChildAt(i);
if (v instanceof TableRow) {
TableRow row = (TableRow) v;
for (int j = 0, jcount = row.getChildCount(); j < jcount; j++) {
View item = row.getChildAt(j);
if (item instanceof Button) {
Button b = (Button) item;
b.setOnClickListener(this);
}
}
}
}
// set the inflated view as what we want to display
this.setContentView(root);
}
public void onClick(View v) {
// we'll just display a simple toast on a button click
Button b = (Button) v;
Toast.makeText(this.anchor.getContext(), b.getText(),
Toast.LENGTH_SHORT).show();
this.dismiss();
}
}
}
The problem is in DemoPopupWindow.onCreate method:
ViewGroup root = (ViewGroup) inflater.inflate(
R.layout.popup_grid_layout, null);
for (int i = 0, icount = root.getChildCount(); i < icount; i++) {
View v = root.getChildAt(i);
if (v instanceof TableRow) {
root will be RelativeLayout defined in popup_grid_layout.xml. Later you iterate through all its children and set onclick listeners only if child view is TableRow, which is never the case. I guess what you want there is to find horizontalScrollView1 view and do the same with its children instead, something like:
View horizontalScrollView1 = findViewById(R.id.horizontalScrollView1);
for (int i = 0, icount = horizontalScrollView1.getChildCount(); i < icount; i++) {
View v = horizontalScrollView1.getChildAt(i);
if (v instanceof TableRow) {
...

Changing EditText height and width on Runtime with some animation

I have Four EditText with different background.
It looks like this:
I want to cover full screen when a EditText is selected with That EditText. For that I need to change the EditText width and height with some animation on Runtime.
When selected It should look like this:
How can I change EditText size with animation on Runtime ?
ANSWER UPDATED :
use this code in drawable/animation_sample.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false">
<translate android:fromXDelta="0%" android:toXDelta="100%" android:fromYDelta="0%" android:toYDelta="0%" android:duration="500" />
And set the animation to the edit text using :
Animation anim=AnimationUtils.loadAnimation( this, R.anim.righttoleft);
editText = (EditText)findViewById(R.id.editText1);
Display display = getWindowManager().getDefaultDisplay();
int width=display.getWidth();
int height = display.getHeight();
editText.setWidth(width);
editText.setHeight(height);
editText.startAnimation(anim);
I'm not sure if it can be done with Animations. In android view takes all space before animation finished, so you will see that other editTexts disappears and selected one slowly increasing. Here is rough example how to do it without standart animations, but changing weights in separate thread:
layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/ll0"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal" >
<EditText
android:id="#+id/et00"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="top|left"
android:text="00" />
<EditText
android:id="#+id/et01"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="top|left"
android:text="01" />
</LinearLayout>
<LinearLayout
android:id="#+id/ll1"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal" >
<EditText
android:id="#+id/et10"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="top|left"
android:text="10" />
<EditText
android:id="#+id/et11"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="top|left"
android:text="11" />
</LinearLayout>
</LinearLayout>
and in code add actions on changing focus:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
OnFocusChangeListener focusListener = new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
LinearLayout parent = (LinearLayout) v.getParent();
EditText forDecresing = null;
for (int i = 0; i < parent.getChildCount(); i++) {
if (parent.getChildAt(i) != v) {
forDecresing = (EditText) parent.getChildAt(i);
break;
}
}
LinearLayout pp = (LinearLayout) parent.getParent();
LinearLayout layoutForDecreasing = null;
for (int i = 0; i < pp.getChildCount(); i++) {
if (pp.getChildAt(i) != parent && pp.getChildAt(i) instanceof LinearLayout) {
layoutForDecreasing = (LinearLayout) pp.getChildAt(i);
break;
}
}
startAnimation((EditText) v, forDecresing, layoutForDecreasing, parent);
} else {
}
}
};
((EditText) findViewById(R.id.et00)).setOnFocusChangeListener(focusListener);
((EditText) findViewById(R.id.et01)).setOnFocusChangeListener(focusListener);
((EditText) findViewById(R.id.et11)).setOnFocusChangeListener(focusListener);
((EditText) findViewById(R.id.et10)).setOnFocusChangeListener(focusListener);
}
public void onBackPressed() {
setWeight(findViewById(R.id.et00), 1);
setWeight(findViewById(R.id.et01), 1);
setWeight(findViewById(R.id.et11), 1);
setWeight(findViewById(R.id.et10), 1);
setWeight(findViewById(R.id.ll1), 1);
setWeight(findViewById(R.id.ll0), 1);
}
Thread animationThread;
private void startAnimation(final EditText forIncreasing, final EditText forDecresing, final LinearLayout layoutForDecreasing,
final LinearLayout layoutForIncreasing) {
if (animationThread != null)
animationThread.interrupt();
animationThread = new Thread(new Runnable() {
#Override
public void run() {
int iterations = 0;
int maxIterations = 30;
setWeight(forIncreasing, maxIterations - 1);
setWeight(layoutForIncreasing, maxIterations - 1);
setWeight(forDecresing, maxIterations - 1);
setWeight(layoutForDecreasing, maxIterations - 1);
while (iterations < maxIterations) {
iterations++;
setWeight(forIncreasing, maxIterations - 1 + iterations);
setWeight(layoutForIncreasing, maxIterations - 1 + iterations);
setWeight(forDecresing, maxIterations - 1 - iterations);
setWeight(layoutForDecreasing, maxIterations - 1 - iterations);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
return;
}
}
animationThread = null;
}
});
animationThread.start();
}
private void setWeight(final View view, final float weight) {
runOnUiThread(new Runnable() {
#Override
public void run() {
LayoutParams params = (LayoutParams) view.getLayoutParams();
params.weight = weight;
view.setLayoutParams(params);
}
});
}
I do not know if this is possible for you, but in this example you can add some more movements quite easy.
I do not recommend use it production, if only you have some other options.
I have tried to explain my Logic for your problem...i hope so it would work for you..
EditText editText = new EditText(this);
editText.setOnClickListener(new OnClickListener() {
public void onClick(){
// Before getSize was introduced (in API level 13), you could use
// the getWidth and getHeight methods that are now deprecated:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
editText.setWidth(width);
editText.setHeight(height);
}
}

Categories

Resources