I am using view pager to show some fragments.
I tried to achieve this by referring this : Android ViewPager - Smooth Transition for this Design
My View pager containing layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical"
android:weightSum="1"
tools:context="com.tpayerapp.Fragments.DepositMoneyFragment">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:clipToPadding="false"
android:layout_above="#+id/indicator"
android:layout_below="#+id/tabs"
android:padding="80dp" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_centerInParent="false"
app:ci_drawable="#drawable/radius"
app:ci_drawable_unselected="#drawable/grey_radius"
app:ci_height="6dp"
app:ci_width="6dp">
</me.relex.circleindicator.CircleIndicator>
Fragment 1 layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
tools:context="com.tpayerapp.Fragments.PayPalFragment">
<ImageView
android:id="#+id/imageView25"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="false"
android:layout_alignParentRight="false"
android:layout_alignParentTop="false"
android:layout_alignWithParentIfMissing="false"
android:layout_centerHorizontal="false"
android:layout_centerInParent="true"
android:background="#color/colorAccent"
app:srcCompat="#drawable/paypal" />
View pager fragment java code:
public class DepositMoneyFragment extends Fragment {
private ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_deposit_money, container, false);
setUpUI(view);
return view;
}
public void setUpUI(View view) {
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);
indicator.setViewPager(viewPager);
viewPager.setPageTransformer(false, new ViewPager.PageTransformer() {
#Override
public void transformPage(View page, float position) {
int pageWidth = viewPager.getMeasuredWidth() - viewPager.getPaddingLeft() - viewPager.getPaddingRight();
int pageHeight = viewPager.getHeight();
int paddingLeft = viewPager.getPaddingLeft();
float transformPos = (float) (page.getLeft() - (viewPager.getScrollX() + paddingLeft)) / pageWidth;
final float normalizedposition = Math.abs(Math.abs(transformPos) - 1);
page.setAlpha(normalizedposition + 0.5f);
int max = -pageHeight / 10;
if (transformPos < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
page.setTranslationY(0);
} else if (transformPos <= 1) { // [-1,1]
page.setTranslationY(max * (1-Math.abs(transformPos)));
} else { // (1,+Infinity]
// This page is way off-screen to the right.
page.setTranslationY(0);
}
}
});
}
#Override
public void onResume() {
super.onResume();
((OnFragmentTitleChangeListener) getActivity()).onFragmentTitle(getResources().getString(R.string.deposite));
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new PayPalFragment(), "");
adapter.addFragment(new PayStackFragment(), "");
adapter.addFragment(new NIBBSFragment(), "");
viewPager.setAdapter(adapter);
}
}
What needs to be done to get this design? Please help. Thank you..
Try Change margin to padding
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="40dp"
android:paddingRight="40dp"
tools:context="com.tpayerapp.Fragments.PayPalFragment">
<ImageView
android:id="#+id/imageView25"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="false"
android:layout_alignParentRight="false"
android:layout_alignParentTop="false"
android:layout_alignWithParentIfMissing="false"
android:layout_centerHorizontal="false"
android:layout_centerInParent="true"
android:background="#color/colorAccent"
app:srcCompat="#drawable/paypal" />
try this link carousel layout with viewpager, if you need more code related to this view, this are main classes you need.
CarouselLinearLayout.java
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;
public class CarouselLinearLayout extends LinearLayout {
private float scale = CarouselPagerAdapter.BIG_SCALE;
public CarouselLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CarouselLinearLayout(Context context) {
super(context);
}
public void setScaleBoth(float scale) {
this.scale = scale;
this.invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// The main mechanism to display scale animation, you can customize it as your needs
int w = this.getWidth();
int h = this.getHeight();
canvas.scale(scale, scale, w/2, h/2);
}
}
CarouselPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class CarouselPagerAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener {
public final static float BIG_SCALE = 1.0f;
public final static float SMALL_SCALE = 0.7f;
public final static float DIFF_SCALE = BIG_SCALE - SMALL_SCALE;
private MainActivity context;
private FragmentManager fragmentManager;
private float scale;
public CarouselPagerAdapter(MainActivity context, FragmentManager fm) {
super(fm);
this.fragmentManager = fm;
this.context = context;
}
#Override
public Fragment getItem(int position) {
// make the first pager bigger than others
try {
if (position == MainActivity.FIRST_PAGE)
scale = BIG_SCALE;
else
scale = SMALL_SCALE;
position = position % MainActivity.count;
} catch (Exception e) {
e.printStackTrace();
}
return ItemFragment.newInstance(context, position, scale);
}
#Override
public int getCount() {
int count = 0;
try {
count = MainActivity.count * MainActivity.LOOPS;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return count;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
try {
if (positionOffset >= 0f && positionOffset <= 1f) {
CarouselLinearLayout cur = getRootView(position);
CarouselLinearLayout next = getRootView(position + 1);
cur.setScaleBoth(BIG_SCALE - DIFF_SCALE * positionOffset);
next.setScaleBoth(SMALL_SCALE + DIFF_SCALE * positionOffset);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
#SuppressWarnings("ConstantConditions")
private CarouselLinearLayout getRootView(int position) {
return (CarouselLinearLayout) fragmentManager.findFragmentByTag(this.getFragmentTag(position))
.getView().findViewById(R.id.root_container);
}
private String getFragmentTag(int position) {
return "android:switcher:" + context.pager.getId() + ":" + position;
}
}
I see you have hard coded the viewPager height to android:layout_height="200dp". Can you try using android:layout_height="match_parent" instead?
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I want to use Cardview in recycle view and need its click event in any class with list position in android java
Step - 1 - Add Recyclerview in your MainActivity Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/idRVCourse"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Step - 2 - For our Card Here We Create New Resource File - layout -> new -> LayoutResourceFile -> New Layout Name / Here i give card_layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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="wrap_content"
android:layout_margin="5dp"
app:cardBackgroundColor="#color/white"
app:cardCornerRadius="8dp"
app:cardElevation="8dp"
app:cardMaxElevation="10dp"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/idIVCourseImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:contentDescription="#string/app_name"
android:padding="5dp"
android:src="#color/black" />
<TextView
android:id="#+id/idTVCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_toEndOf="#id/idIVCourseImage"
android:text="course_name"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
Step - 3 - Now We have to create one class for Model/Item, Here i make New class by name CourseModel
public class CourseModel {
private String course_name;
private int course_image;
// Constructor
public CourseModel(String course_name, int course_image) {
this.course_name = course_name;
this.course_image = course_image;
}
public String getCourse_name() {
return course_name;
}
public void setCourse_name(String course_name) {
this.course_name = course_name;
}
public int getCourse_image() {
return course_image;
}
public void setCourse_image(int course_image) {
this.course_image = course_image;
}
}
Step - 4 - Here we Have to make new Class as a Adapter here i give name CourseAdapter
public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.Viewholder> {
private Context context;
private ArrayList<CourseModel> courseModelArrayList;
// i3 create interface variable & add in constructor & solve main activity error by pass this in new CourseAdapter
OnItemClickListener onItemClickListener;
CourseModel item;
public CourseAdapter(Context context, ArrayList<CourseModel> courseModelArrayList, OnItemClickListener onItemClickListener) {
this.context = context;
this.courseModelArrayList = courseModelArrayList;
this.onItemClickListener = onItemClickListener;
}
#NonNull
#Override
public CourseAdapter.Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull CourseAdapter.Viewholder holder, int position) {
CourseModel model = courseModelArrayList.get(position);
holder.courseNameTV.setText(model.getCourse_name());
holder.courseIV.setImageResource(model.getCourse_image());
// can also set click event from Adapter class
/*holder.courseIV.setOnClickListener(v -> {
Toast.makeText(context, " -> "+model.getCourse_name(), Toast.LENGTH_SHORT).show();
});*/
}
#Override
public int getItemCount() {
return courseModelArrayList.size();
}
public class Viewholder extends RecyclerView.ViewHolder {
private ImageView courseIV;
private TextView courseNameTV;
public Viewholder(#NonNull View itemView) {
super(itemView);
courseIV = itemView.findViewById(R.id.idIVCourseImage);
courseNameTV = itemView.findViewById(R.id.idTVCourseName);
// i5
itemView.setOnClickListener(view -> {
onItemClickListener.onItemClick(item,getAdapterPosition());
notifyDataSetChanged();
});
}
}
}
Step - 5 - Now Lets Create Interface here i make interface by name OnItemClickListener
// I1
public interface OnItemClickListener {
void onItemClick(CourseModel item, int position);
void onLongItemClick(CourseModel item, int position);
}
Step - 6 - In This Last Step Apply Below code in Main Activity Here in ItemList You Can Put Your Images of Drawble
// i2 implement interface & solve error
public class MainActivity extends AppCompatActivity implements OnItemClickListener{
private RecyclerView courseRV;
private ArrayList<CourseModel> courseItemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
courseRV = findViewById(R.id.idRVCourse);
itemList();
// i4
CourseAdapter courseAdapter = new CourseAdapter(this, courseItemList,this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
courseRV.setLayoutManager(linearLayoutManager);
courseRV.setAdapter(courseAdapter);
}
private void itemList() {
courseItemList = new ArrayList<>();
courseItemList.add(new CourseModel("C", R.drawable.ic_launcher_background));
courseItemList.add(new CourseModel("C++", R.drawable.ic_launcher_background));
courseItemList.add(new CourseModel("Java", R.drawable.ic_launcher_background));
courseItemList.add(new CourseModel("Android", R.drawable.ic_launcher_background));
courseItemList.add(new CourseModel("Flutter", R.drawable.ic_launcher_background));
courseItemList.add(new CourseModel("HTML", R.drawable.ic_launcher_background));
courseItemList.add(new CourseModel("CSS", R.drawable.ic_launcher_background));
}
// i6
#Override
public void onItemClick(CourseModel item, int position) {
Toast.makeText(this, ""+position+"\n"+courseItemList.get(position).getCourse_name(), Toast.LENGTH_SHORT).show();
}
#Override
public void onLongItemClick(CourseModel item, int position) {
}
}
I am not that experienced in Java so I can't figure it out myself.
I bought a template with a tablayout which looks like this (image 1):
I want to disable the swipe function between these two tabs, so it should only be possible to get to "TAB 2" by clicking on the tab "TAB 2".
There are a lot of tutorials in the Internet but non of them fits to my code so I'm a bit confused.
Here is my TabFragment:
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
if(position == 0){
return new Tab1();
}
if(position == 1){
return new Tab2();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Tab 1";
case 1 :
return "Tab 2";
}
return null;
}
}}
and my tab_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabGravity="fill"
app:tabMode="fixed"
android:background="#color/material_blue_grey_800"
app:tabIndicatorColor="#color/orange"
app:tabSelectedTextColor="#color/orange"
app:tabTextColor="#color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="50dp">
</android.support.v4.view.ViewPager>
</LinearLayout>
I tried my best to figure out how to solve it but didn't succeed, so I hope one of you can help me with this small problem :)
Thanks a lot.
You need to create a custom ViewPager that intercepts the onTouch events and avoid the default behaviour. This way the user wont be able to swipe between pages but will be able to touch on the tabs.
You can check this link where is already answered: How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?
EDIT
I'll explain it by steps:
Create a new class called NonSwipeableViewPager
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.lang.reflect.Field;
public class NonSwipeableViewPager extends ViewPager {
public NonSwipeableViewPager(Context context) {
super(context);
setMyScroller();
}
public NonSwipeableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
setMyScroller();
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
//down one is added for smooth scrolling
private void setMyScroller() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
scroller.set(this, new MyScroller(getContext()));
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyScroller extends Scroller {
public MyScroller(Context context) {
super(context, new DecelerateInterpolator());
}
#Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
}
}
}
Modify your layout to use the new ViewPager
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabGravity="fill"
app:tabMode="fixed"
android:background="#color/material_blue_grey_800"
app:tabIndicatorColor="#color/orange"
app:tabSelectedTextColor="#color/orange"
app:tabTextColor="#color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
<NonSwipeableViewPager <!-- You will need to import this correctly with your class package -->
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="50dp">
</NonSwipeableViewPager>
</LinearLayout>
Update your activity with the new ViewPager
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static NonSwipeableViewPager viewPager; // This line changed
public static int int_items = 2 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (NonSwipeableViewPager) x.findViewById(R.id.viewpager); // This line changed
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
You can keep the same adapter MyAdapter.
This will avoid the swipe between tabs but will keep the click on each one.
I know this is quite old but you need to switch to ViewPager2.
ViewPager2 replaces androidx.viewpager.widget.ViewPager, addressing most of its predecessor’s pain-points, including right-to-left layout support, vertical orientation, modifiable Fragment collections, etc.
If you need to disable user swipe support then you can call:
viewPager2.isUserInputEnabled = false
I have implemented Gridview, but the images from the phone gallery is not appearing in the particular GridView.
The scroll seems to be big enough as the scrollbar appearing on the right side scrolls along to the bottom. Then why I couldn't see the images.
GalleryGridAdapter.java
package com.test.Adapter;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import com.test.R;
public class GalleryGridAdapter extends CursorAdapter
{
private Context mContext;
private Cursor mCursor;
private int mColumnIndex;
private ImageView imageView;
#SuppressWarnings("deprecation")
public GalleryGridAdapter(Context context, Cursor c, int ci) {
super(context, c);
mContext = context;
mCursor = c;
mColumnIndex = ci;
}
#Override
public void bindView(View view, Context context, Cursor curs)
{
ImageView imageView = (ImageView) view;
int id = curs.getInt(mColumnIndex);
imageView.setImageURI( Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
String.valueOf(id)));
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
#Override
public View newView(Context context, Cursor curs, ViewGroup parent)
{
return new ImageView(context);
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public int mygetItemId(int position) {
return 0;
}
}
MyActivity.java
String[] projection = {MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.DATA};
final Cursor cursor = context.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null,
MediaStore.Images.Thumbnails.IMAGE_ID);
int columnIndex = 0;
if (cursor != null) {
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
GridView gridview = (GridView) findViewById(R.id.gridViewGallery);
gridview.setAdapter(new GalleryGridAdapter(getApplicationContext(), cursor, columnIndex));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("selected Image",cursor.getColumnName(i)+"");
}
});
}
use xml code like :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#drawable/bg_child">
<FrameLayout android:id="#+id/FrameLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<FrameLayout android:id="#+id/LinearLayout01"
android:layout_gravity="top" android:layout_height="50dp" android:layout_width="fill_parent">
<TextView android:id="#+id/TextView01"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:layout_gravity="center_vertical" android:layout_marginLeft="30dp" android:gravity="center_vertical" android:drawableLeft="#drawable/photo_frame" android:textColor="#color/grey" android:text="#string/photogallery_txt"></TextView>
<Button android:layout_gravity="right" android:id="#+id/btnMoreInfo" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:textStyle="bold" android:background="#drawable/my_child_button" android:layout_width="100dp" android:layout_height="40dp" android:text="#string/moreinfo_txt"></Button>
</FrameLayout>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:columnWidth="90dp"
android:numColumns="auto_fit" android:verticalSpacing="10dp"
android:horizontalSpacing="10dp" android:stretchMode="columnWidth"
android:gravity="center" android:layout_gravity="bottom"
android:layout_marginTop="50dp"/>
</FrameLayout>
use code like :
public class GalleryPage extends Activity {
private static Uri[] mUrls = null;
private static String[] strUrls = null;
private String[] mNames = null;
private GridView gridview = null;
private Cursor cc = null;
private Button btnMoreInfo = null;
private ProgressDialog myProgressDialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
btnMoreInfo = (Button) findViewById(R.id.btnMoreInfo);
// It have to be matched with the directory in SDCard
cc = this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
null);
if (cc != null) {
myProgressDialog = new ProgressDialog(GalleryPage.this);
myProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
myProgressDialog.setMessage(getResources().getString(R.string.pls_wait_txt));
myProgressDialog.show();
new Thread() {
public void run() {
try {
cc.moveToFirst();
mUrls = new Uri[cc.getCount()];
strUrls = new String[cc.getCount()];
mNames = new String[cc.getCount()];
for (int i = 0; i < cc.getCount(); i++) {
cc.moveToPosition(i);
mUrls[i] = Uri.parse(cc.getString(1));
strUrls[i] = cc.getString(1);
mNames[i] = cc.getString(3);
//Log.e("mNames[i]",mNames[i]+":"+cc.getColumnCount()+ " : " +cc.getString(3));
}
} catch (Exception e) {
}
myProgressDialog.dismiss();
}
}.start();
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(GalleryPage.this, BigImage.class);
Log.e("intent : ", ""+position);
i.putExtra("imgUrls", strUrls);
i.putExtra("position", position);
startActivity(i);
}
});
}
btnMoreInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(GalleryPage.this, ChildLogin.class);
startActivity(i);
}
});
}
/**
* This class loads the image gallery in grid view.
*
*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return cc.getCount();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.galchild, null);
try {
ImageView imageView = (ImageView) v.findViewById(R.id.ImageView01);
//imageView.setScaleType(ImageView.ScaleType.FIT_XY);
// imageView.setPadding(8, 8, 8, 8);
Bitmap bmp = decodeURI(mUrls[position].getPath());
//BitmapFactory.decodeFile(mUrls[position].getPath());
imageView.setImageBitmap(bmp);
//bmp.
TextView txtName = (TextView) v.findViewById(R.id.TextView01);
txtName.setText(mNames[position]);
} catch (Exception e) {
}
return v;
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
FlurryAgent.onStartSession(this, "***");
}
/**
* This method is to scale down the image
*/
public Bitmap decodeURI(String filePath){
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Only scale if we need to
// (16384 buffer for img processing)
Boolean scaleByHeight = Math.abs(options.outHeight - 100) >= Math.abs(options.outWidth - 100);
if(options.outHeight * options.outWidth * 2 >= 16384){
// Load, scaling to smallest power of 2 that'll get it <= desired dimensions
double sampleSize = scaleByHeight
? options.outHeight / 100
: options.outWidth / 100;
options.inSampleSize =
(int)Math.pow(2d, Math.floor(
Math.log(sampleSize)/Math.log(2d)));
}
// Do the actual decoding
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[512];
Bitmap output = BitmapFactory.decodeFile(filePath, options);
return output;
}
}
I have a relative layout which contains an image. I have like 10-20 images in drawable folder and a hashmap which stores these images.
On swiping below the image from left to right, it should change to next image.
On each swipe, it should change to next image from hashmap.
I am completely new to java and android programming and help in any way is appreciated.
This is what I have:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.bschiranth.homework2_chiranthbs.MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/alice"
android:onClick="onClick"
android:clickable="true"
android:src="#drawable/alice"/>
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/zoombar"
android:max="100"
android:progress="50"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
and my java:
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.d("fling", "doing fling");
MovieData movieData = new MovieData();
HashMap hashMap = new HashMap();
for(int i=1;i<movieData.getSize();i++)
{
hashMap = movieData.getItem(i);
}
if(event1.getX()-event2.getX()> SWIPE_MIN_DISTANCE && Math.abs(velocityX)>SWIPE_THRESHOLD_VELOCITY)
{
Toast.makeText(Activity_Control.this,
"its flinging right to left", Toast.LENGTH_SHORT).show();
imageView.setImageResource(R.drawable.avatar);
}
if(event2.getX()-event1.getX()> SWIPE_MIN_DISTANCE && Math.abs(velocityX)>SWIPE_THRESHOLD_VELOCITY)
{
Toast.makeText(Activity_Control.this,
"its flinging left to right", Toast.LENGTH_SHORT).show();
imageView.setImageResource(R.drawable.avengers);
}
return true;
}
Better you can use view pager instead of imageview
<?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" >
<android.support.v4.view.ViewPager
android:id="#+id/myfivepanelpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ViewPagerAdapter.java
import android.app.Activity;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
public class ViewPagerAdapter extends PagerAdapter {
Activity activity;
int imageArray[];
public ViewPagerAdapter(Activity act, int[] imgArra) {
imageArray = imgArra;
activity = act;
}
public int getCount() {
return imageArray.length;
}
public Object instantiateItem(View collection, int position) {
ImageView view = new ImageView(activity);
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
view.setScaleType(ScaleType.FIT_XY);
view.setBackgroundResource(imageArray[position]);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
PageIndicatorActivity.java
public class PageIndicatorActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
R.drawable.antartica3, R.drawable.antartica4,
R.drawable.antartica5, R.drawable.antartica6,
R.drawable.antartica7, R.drawable.antartica8 };
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
public int getCount() {
return imageArray.length;
}
public Object instantiateItem(View collection, int position) {
ImageView view = new ImageView(activity);
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
view.setScaleType(ScaleType.FIT_XY);
view.setBackgroundResource(imageArray[position]);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
This can be done by ViewFlipper as described below.
This is your Activity.xml file
<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/view_flipper"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HowToUseActivity" >
<ImageView
android:id="#+id/imageHowToUse"
android:contentDescription="#string/app_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#mipmap/screen_1" />
</ViewFlipper>
declare required variables in your activity class
private int number = 0;
private float initialX;
private ImageView imageView;
in your Activity's onCreate(...) method retrieve the ImageView
imageView = (ImageView) findViewById(R.id.imageHowToUse);
override the method onTouchEvent(...) in same activity
#Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = event.getX();
break;
case MotionEvent.ACTION_UP:
float finalX = event.getX();
if (initialX > finalX) {
if (number >= 3) {
break;
}
next();
} else {
if(number <= 0) {
break;
}
previous();
}
break;
}
return false;
}
private void next() {
number++;
imageView.setImageResource(getImage());
}
private void previous() {
number--;
imageView.setImageResource(getImage());
}
then write method getImage() to get next image you want to display
private int getImage() {
int resource = R.mipmap.screen_1;
switch(number) {
case 0:
resource = R.mipmap.screen_1;
break;
case 1:
resource = R.mipmap.screen_2;
break;
case 2:
resource = R.mipmap.screen_3;
break;
}
return resource;
}
this is working code in my project. It'll help you.
NOTE : R.mipmap.screen_* is the image resource present in my resource directory.
I have public class PageFragment that extends Fragment to create 6 pages with views that fills by another class.
Here are the PageFragment class:
public class PageFragment extends Fragment {
static final String arg_page_number = "arg_page_number";
int pageNumber;
int backColor;
public LinearLayout framesContainer;
ExecutorService ex = Executors.newCachedThreadPool();
Future<ArrayList<ElementData>> s = ex.submit(new MyThread());
public static PageFragment newInstance(int page) {
PageFragment pageFragment = new PageFragment();
Bundle arguments = new Bundle();
arguments.putInt(arg_page_number, page);
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(arg_page_number);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.table_row, null);
framesContainer = (LinearLayout) view.findViewById(R.id.frames_container);
for (int i = 0; i < 20; i += 4) {
Frame frame = new Frame(getApplicationContext());
try {
frame.setStudyName(s.get().get(0).Days().get(i));
frame.setStudyKindName(s.get().get(0).Days().get(i + 1));
frame.setAuditorium(s.get().get(0).Days().get(i + 2));
frame.setLectureTitle(s.get().get(0).Days().get(i + 3));
framesContainer.addView(frame);
} catch (Exception e) {
e.printStackTrace();
}
}
return view;
}
class MyThread implements Callable<ArrayList<ElementData>> {
public ArrayList<ElementData> call() {
ArrayList<ElementData> elementDataArrayList = Parser.parse("url");
return elementDataArrayList;
}
}}
And this is MyActivity:
public class MyActivity extends FragmentActivity {
/**
* Called when the activity is first created.
*/
static final String TAG = "myLogs";
static final int PAGE_COUNT = 6;
ViewPager pager;
PagerAdapter pagerAdapter;
SharedPreferences sPref;
String[] groups = {....};
final String SAVED_TEXT = "SavePref";
private LinearLayout framesContainer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sPref = getPreferences(MODE_PRIVATE);
if (sPref.getBoolean(SAVED_TEXT, true)) {
setContentView(R.layout.startpage);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, groups);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
spinner.setAdapter(adapter);
final int selectionCurrent = spinner.getSelectedItemPosition();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if (selectionCurrent != position) {
sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putBoolean(SAVED_TEXT, false);
ed.commit();
setContentView(R.layout.main);
pager = (ViewPager) findViewById(R.id.frames_container);
pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.d(TAG, "onPageSelected, position = " + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
} else {
setContentView(R.layout.main);
pager = (ViewPager) findViewById(R.id.frames_container);
pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.d(TAG, "onPageSelected, position = " + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
}}
When i'm using getApplicationContext is shows me error of unresolved method.
Do i need to cast MyActivity's context here? How can i do that?
Frame class:
public class Frame extends RelativeLayout {
private TextView StudyName;
private TextView Auditorium;
private TextView StudyKindName;
private TextView LectureTitle;
public Frame(Context context) {
super(context);
initComponent();
}
private void initComponent() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.table_row, this);
StudyName = (TextView) findViewById(R.id.StudyName);
Auditorium = (TextView) findViewById(R.id.Auditorium);
StudyKindName = (TextView) findViewById(R.id.StudyKindName);
LectureTitle = (TextView) findViewById(R.id.LectureTitle);
}
public void setStudyName(String study_Name) {
StudyName.setText(study_Name);
}
public void setAuditorium(String auditorium) {
Auditorium.setText(auditorium);
}
public void setStudyKindName(String studyKindName) {
StudyKindName.setText(studyKindName);
}
public void setLectureTitle(String lectureTitle) {
LectureTitle.setText(lectureTitle);
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/frames_container"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
</android.support.v4.view.ViewPager>
</RelativeLayout>
table_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/program_frame"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip">
<TextView
android:id="#+id/StudyName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textColor="#android:color/white"
android:textStyle="normal"
android:textSize="16sp"
android:text="StudyName"/>
<TextView
android:id="#+id/Auditorium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:textColor="#android:color/darker_gray"
android:textStyle="bold"
android:textSize="16sp"
android:singleLine="true"
android:text="Auditorium"/>
<TextView
android:id="#+id/StudyKindName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/StudyName"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dip"
android:textColor="#android:color/darker_gray"
android:textStyle="bold"
android:textSize="15sp"
android:singleLine="true"
android:text="StudyKindName"/>
<TextView
android:id="#+id/LectureTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/StudyKindName"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dip"
android:textColor="#android:color/darker_gray"
android:textStyle="normal"
android:textSize="12sp"
android:text="Lector"/>
<ImageView
android:id="#+id/imageView2"
android:layout_below="#id/LectureTitle"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="15dip"
android:background="#bb333333" />
</RelativeLayout>
You can use getActivity().getApplicationContext() in Fragment.
I don't know what Frame is in Frame frame = new Frame(getApplicationContext());. In case you are doing ui stuff use only getActivity().
Read
When to call activity context OR application context?