How to convert ViewPager implementation using Data binding? - android

MainActvity:
public class MainActivity extends AppCompatActivity {
private static int currentPage = 0;
private static int NUM_PAGES = 0;
CirclePageIndicator indicator;
int Imageitems[] = {R.drawable.hike, R.drawable.hike, R.drawable.hike};
final ArrayList<Integer> imageItems = new ArrayList<>();
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = (ViewPager) findViewById(R.id.pager);
indicator = (CirclePageIndicator)
findViewById(R.id.indicator);
for (int i = 0; i < Imageitems.length; i++) {
imageItems.add(Imageitems[i]);
}
ImageSlider(imageItems);
}
private void ImageSlider(ArrayList<Integer> ImagesArray) {
mPager.setAdapter(new Item_SlidingImage_Adapter(this, ImagesArray));
indicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density);
NUM_PAGES = ImagesArray.size();
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);
// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<data>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativelayout1"
android:layout_width="match_parent"
android:layout_height="150dp"
>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:addOnPageChangeListener="#{data.pageChangeListener}"
app:currentItem="#{data.currentPage}"
app:adapter="#{image_adapter}"
/>
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:padding="5dp"
app:centered="true"
app:fillColor="#ff0099"
app:pageColor="#FF0000"
app:radius="#{data.density}"
app:snap="false" />
</RelativeLayout>
</LinearLayout>
</layout>
adapter:
public class Item_SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
public Item_SlidingImage_Adapter(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, final int position) {
View imageLayout = inflater.inflate(R.layout.slidingimages_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;
}
}
item.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="1dip" >
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:scaleType="fitXY" />
</FrameLayout>
Using given code I am able to auto flip in ViewPager and also using manually with some delay. I have to convert same code using Databinding; I tried but I am not able to understand how to set adapter,currentitem, and on page change listener how I will set value in xml?
How can I convert existing code for databinding in Android?

Related

Adapter not attach skipping layout

I am getting an error saying no adapter attach skipping layout.and the list doesn't appear in when emulator runs.please help.I cant see anything in list.screen appears blank.other items in the activity are appearing.i have seen almost all answer on the internet but didn't get any solution .and also when i tried to make a listview in other tab i got the list.
this is songsTab Activity
public class SongsTab extends Fragment {
private ArrayList<songInfo> songs = new ArrayList<songInfo>();
RecyclerView recyclerView;
SeekBar seekBar;
songAdapter songAdapter1;
MediaPlayer mediaPlayer;
Cursor cursor;
private Handler myHandler = new Handler();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.songs, container, false);
recyclerView = (RecyclerView)v. findViewById(R.id.recyclerView);
seekBar = (SeekBar) v.findViewById(R.id.seekBar);
songAdapter1 = new songAdapter(songs, getActivity());
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
linearLayoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(songAdapter1);
solved();
checkUserPermission();
Thread t = new runThread();
t.start();
return v;
}
public void solved() {
songAdapter1.setOnitemClickListener(new songAdapter.OnitemClickListener() {
#Override
public void onItemclick(songAdapter.ViewHolder holder, View v, final songInfo obj, int position) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} else {
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(obj.getSongPath());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
Log.d("Prog", "run: " + mediaPlayer.getDuration());
}
});
} catch (Exception e) {
}
}
};
myHandler.postDelayed(runnable, 100);
}
}
});
}
public class runThread extends Thread {
#Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("Runwa", "run: " + 1);
if (mediaPlayer != null) {
seekBar.post(new Runnable() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
});
Log.d("Runwa", "run: " + mediaPlayer.getCurrentPosition());
}
}
}
}
private void checkUserPermission(){
if(Build.VERSION.SDK_INT>=23){
if(ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},123);
return;
}
}
loadSongs();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 123:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
loadSongs();
}else{
Toast.makeText(getContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
checkUserPermission();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void loadSongs(){
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC+"!=0";
cursor = getContext().getContentResolver().query(uri,null,selection,null,null);
if(cursor != null) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String SongPath = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
songInfo s = new songInfo(name, artist, SongPath);
songs.add(s);
} while (cursor.moveToNext());
}
cursor.close();
songAdapter1 = new songAdapter(songs, getActivity());
}
}
}
this is my Adapter
public class songAdapter extends RecyclerView.Adapter<songAdapter.ViewHolder> {
ArrayList<songInfo> songs;
Context context;
OnitemClickListener onitemClickListener;
public songAdapter(ArrayList<songInfo> songs, Context context) {
this.songs = songs;
this.context = context;
}
public interface OnitemClickListener{
void onItemclick(ViewHolder holder, View v, songInfo obj, int position);
}
public void setOnitemClickListener(OnitemClickListener onitemClickListener)
{
this.onitemClickListener=onitemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mView= LayoutInflater.from(context).inflate(R.layout.card,parent,false);
return new ViewHolder(mView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final songInfo song = songs.get(position);
holder.songName.setText(songs.get(position).getSongName());
holder.artistName.setText(songs.get(position).getArtistName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(onitemClickListener!=null)
{
onitemClickListener.onItemclick(holder,view,song,position);
}
}
});
}
#Override
public int getItemCount() {
return songs.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView songName,artistName;
public ViewHolder(View itemView) {
super(itemView);
songName=(TextView)itemView.findViewById(R.id.songName);
artistName=(TextView)itemView.findViewById(R.id.artistName);
}
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
public ViewPagerAdapter pagerAdapter;
private ViewPager mViewPager;
private Toolbar toolbar;
private TabLayout tabLayout;
public static View rootView;
public static int tabNo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setAdapter(pagerAdapter);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabNo = tab.getPosition();
mViewPager.setCurrentItem(tabNo);//setting current selected item over viewpager
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// View rootView;
switch (getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1: {
rootView = inflater.inflate(R.layout.songs, container, false);
break;
}
case 2: {
rootView = inflater.inflate(R.layout.album, container, false);
break;
}
case 3: {
rootView = inflater.inflate(R.layout.genres, container, false);
break;
}
case 4: {
rootView = inflater.inflate(R.layout.artist, container, false);
break;
}
}
return rootView;
}
}
}
recyclerView xml
<?xm 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"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollView">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="150dp"
android:id="#+id/recyclerView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/seekBar" />
</ScrollView>
<SeekBar
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/seekBar"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="37dp"
android:indeterminate="false" />
</RelativeLayout>
this is cardView
<?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">
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardBackgroundColor="#f5fffa"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/songName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Shape of you"
android:maxLines="1"/>
<TextView
android:id="#+id/artistName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="Ed Sheeran"
android:maxLines="1"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
mainActivity xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.murarilal.musicmania.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Don't initialize songAdapter1 again inside loadSongs().
Create a method like this in songAdapter class:
public void notifySongAdded(ArrayList<songInfo> songs) {
this.songs = songs;
notifyDataSetChanged();
}
And call songAdapter1.notifySongAdded(songs); after adding songs inside loadSongs().

image swiping not working in android view pager

I want to create an app which swipe images left/right so i use viewPager for this i run this code it gets run successfully but blank screen comes nothing happens.
This is my homeSwipe Class
public class homeSwipe extends Activity {
ViewPager viewPager;
customPagerAdapter customPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_swipe);
viewPager = (ViewPager) findViewById(R.id.pager);
customPagerAdapter = new customPagerAdapter(homeSwipe.this);
viewPager.setAdapter(customPagerAdapter);
}
}
that is my layout.xml:
<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:orientation="vertical">
<android.support.v4.view.ViewPager 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:id="#+id/pager">
</android.support.v4.view.ViewPager>
</RelativeLayout>
This is my customPagerAdapter class
public class customPagerAdapter extends PagerAdapter {
private int imgres[] ={R.drawable.graypatternbackground,R.drawable.home,R.drawable.homescreen,R.drawable.redwall};
private Context context;
private LayoutInflater layoutInflater;
public customPagerAdapter(Context context){
this.context =context;
}
#Override
public int getCount() {
return imgres.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View item_view =(View)layoutInflater.inflate(R.layout.swipelayout,container,false);
ImageView imgView = (ImageView)item_view.findViewById(R.id.imageView);
imgView.setImageResource(imgres[position]);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
This is my swipelayout.xml file
<?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">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"/>
</LinearLayout>
This is custompagerAdapter.
import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentStatePagerAdapter;public class PropTypePagerAdapter extends FragmentStatePagerAdapter { int noOfTab; public PropTypePagerAdapter(FragmentManager fm ,int noOfTab) { super(fm); this.noOfTab=noOfTab; } #Override public Fragment getItem(int position) { switch (position) { case 0: return new PropTabType(0); case 1: return new PropTabType(1); case 2: return new PropTabType(2); case 3: PropTabType service = new PropTabType(3); return service; } } #Override public int getCount() {
return noOfTab;
}
}
And this is logic for swapping image
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {view = inflater.inflate(R.layout.fragment_prop_type_tab,container, false);fragImg = (ImageView) view.findViewById(R.id.fragImg); if (position == 0) { fragImg.setImageResource(R.drawable.buy); } else if (position == 1) { fragImg.setImageResource(R.drawable.rent1); } else { fragImg.setImageResource(R.drawable.hostel); } return view; }

Setting OnClick to ViewPager not functioning

I am having some trouble with implementing OnItemClick to the ViewPager.
I would like it so when I click on one of my picture's being displayed by the ViewPager, it displays a toast message just to tell me that this is working.
So far, nothing happens when I click on one of my items when doing this.
Any help would be appreciated!
ViewPager XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="#+id/rellayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</android.support.v4.view.ViewPager>
<com.google.ads.AdView
android:id="#+id/ad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adSize="BANNER"
ads:adUnitId="AdIdHere"
ads:loadAdOnCreate="true" >
</com.google.ads.AdView>
</RelativeLayout>
ImageDetail Fragment class:
public class ImageDetailFragment extends Fragment {
private static final String IMAGE_DATA_EXTRA = "extra_image_data";
private String mImageUrl;
private ImageView mImageView;
private ImageFetcher mImageFetcher;
public static ImageDetailFragment newInstance(String imageUrl) {
final ImageDetailFragment f = new ImageDetailFragment();
final Bundle args = new Bundle();
args.putString(IMAGE_DATA_EXTRA, imageUrl);
f.setArguments(args);
return f;
}
public ImageDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageUrl = getArguments() != null ? getArguments().getString(
IMAGE_DATA_EXTRA) : null;
}
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
context = v.getContext();
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(context, "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (Batmanark.class.isInstance(getActivity())) {
mImageFetcher = ((Batmanark) getActivity()).getImageFetcher();
mImageFetcher.loadImage(mImageUrl, mImageView);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mImageView != null) {
ImageWorker.cancelWork(mImageView);
mImageView.setImageDrawable(null);
}
}
}
Fragment detail XML:
<?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="fill_parent" >
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<com.question.ui.RecyclingImageView
android:id="#+id/imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:contentDescription="#string/imageview_description" />
</FrameLayout>
ViewPager Class:
public class Batmanark extends FragmentActivity implements OnClickListener {
private static final String IMAGE_CACHE_DIR = "images";
public static final String EXTRA_IMAGE = "extra_image";
private ImagePagerAdapter mAdapter;
private ImageFetcher mImageFetcher;
private ViewPager mPager;
#TargetApi(11)
#Override
public void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG) {
Utils.enableStrictMode();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.image_detail_pager);
AdView ad = (AdView) findViewById(R.id.ad);
ad.loadAd(new AdRequest());
final DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int height = displayMetrics.heightPixels;
final int width = displayMetrics.widthPixels;
final int longest = (height > width ? height : width) / 2;
ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(
this, IMAGE_CACHE_DIR);
cacheParams.setMemCacheSizePercent(0.25f);
mImageFetcher = new ImageFetcher(this, longest);
mImageFetcher.addImageCache(getSupportFragmentManager(), cacheParams);
mImageFetcher.setImageFadeIn(false);
mAdapter = new ImagePagerAdapter(getSupportFragmentManager(),
Images.imageUrlsBatmanark.length);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setPageMargin((int) getResources().getDimension(
R.dimen.image_detail_pager_margin));
mPager.setOffscreenPageLimit(2);
getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
if (Utils.hasHoneycomb()) {
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
mPager.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
#Override
public void onSystemUiVisibilityChange(int vis) {
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
actionBar.hide();
} else {
actionBar.show();
}
}
});
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
actionBar.hide();
}
final int extraCurrentItem = getIntent().getIntExtra(EXTRA_IMAGE, -1);
if (extraCurrentItem != -1) {
mPager.setCurrentItem(extraCurrentItem);
}
}
#Override
public void onResume() {
super.onResume();
mImageFetcher.setExitTasksEarly(false);
}
#Override
protected void onPause() {
super.onPause();
mImageFetcher.setExitTasksEarly(true);
mImageFetcher.flushCache();
}
#Override
protected void onDestroy() {
super.onDestroy();
mImageFetcher.closeCache();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.clear_cache:
mImageFetcher.clearCache();
Toast.makeText(this, R.string.clear_cache_complete_toast,
Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
public ImageFetcher getImageFetcher() {
return mImageFetcher;
}
private class ImagePagerAdapter extends FragmentStatePagerAdapter {
private final int mSize;
public ImagePagerAdapter(FragmentManager fm, int size) {
super(fm);
mSize = size;
}
#Override
public int getCount() {
return mSize;
}
#Override
public Fragment getItem(int position) {
return ImageDetailFragment
.newInstance(Images.imageUrlsBatmanark[position]);
}
}
#TargetApi(11)
#Override
public void onClick(View v) {
final int vis = mPager.getSystemUiVisibility();
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
} else {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
}
}
you need to set click event on view in ImageDetailFragment
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
context = v.getContext();
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(context, "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
mImageView = (ImageView) v.findViewById(R.id.imageView);
return v;
}

How to display video in VideoView in the center of the screen?

I am creating ViewPager with two VideoViews. On sliding pages, video on current page start playing. One problem: how to display video in VideoView in the center of the screen ?
Here is my code,
MainActivity.java:
public class MainActivity extends Activity{
private class MyViewPagerAdapter extends PagerAdapter implements ViewPager.OnPageChangeListener
{
private Vector<View> pages;
private ViewGroup myContainer;
private int currentPageId;
private boolean flag;
public MyViewPagerAdapter(Context context, Vector<View> pages)
{
this.pages=pages;
}
#Override
public int getCount()
{
return pages.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position)
{
flag = true;
currentPageId = 0;
int positionNow = myPager.getCurrentItem();
View page = pages.get(position);
container.addView(page);
myContainer = container;
if(positionNow == position)
StartVideo(container, positionNow);
return page;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((View) object);
myContainer = container;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view.equals(object);
}
#Override
public void onPageScrollStateChanged(int arg0)
{
if(flag)
{
MyVideoView currVideo = (MyVideoView) myContainer.getChildAt(currentPageId+1);
if(currVideo != null)
if(currVideo.getVideoPath() != null)
currVideo.pause();
}
else
flag = !flag;
}
#Override
public void onPageSelected(int arg0)
{
flag = false;
currentPageId = myPager.getCurrentItem();
StartVideo(myContainer, myPager.getCurrentItem());
}
private void StartVideo(ViewGroup container, int position)
{
View page = container.getChildAt(position+1);
MyVideoView curVideo = (MyVideoView) page;
Log.d("Andrew", curVideo.getVideoPath());
curVideo.start();
}
}
private ViewPager myPager;
private MyViewPagerAdapter myAdapter;
private Vector<View> pages;
private MyVideoView myVideoView;
int currentPage, previousPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pages = new Vector<View>();
for(int i=1; i <= 2; i++)
{
myVideoView = new MyVideoView(this);
myVideoView.setVideoPath("videoPath");
pages.add(myVideoView);
}
this.myAdapter = new MyViewPagerAdapter(this, pages);
this.myPager = (ViewPager) this.findViewById(R.id.viewpageronecard);
this.myPager.setAdapter(myAdapter);
myPager.setOnPageChangeListener(myAdapter);
myPager.setOffscreenPageLimit(1);
myPager.setCurrentItem(0);
}
}
activity_main.xml:
<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/viewpageronecard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#222222" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
Although it is an old question, perhaps someone else is struggling with it, too, as I had the same problem. I solved it by changing
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
to
android:layout_gravity="center"
in the xml for the VideoView I used to populate the ViewPager.

padding_medium cannot be resolved or is not a field error

I have a view pager to view images in Swipe horizontal fashion. I am populating view pager with my ImageFragmentAdapter class which extends FragmentPagerAdapter. In my ImageFragmentAdapter .java, i am gettin an error in this line
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
Error is : padding_medium cannot be resolved or is not a field
I just googled about the issue, I came to know that i should add this line to imports.
import your.application.packagename.R;
But still i get error on this line. can anyone tell what is the problem.?
ImageFragmentAdapter .java
public class ImageFragmentAdapter extends FragmentPagerAdapter implements
IconPagerAdapter
{
private int[] CONTENT = new int[] {
R.drawable.gallery_photo_1,
R.drawable.gallery_photo_2,
R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4
};
protected static final int[] ICONS = new int[] { R.drawable.marker,
R.drawable.marker, R.drawable.marker, R.drawable.marker };
private int mCount = CONTENT.length;
public ImageFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ImageFragment.newInstance(CONTENT[position % CONTENT.length]);
}
#Override
public int getCount() {
return mCount;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.appContext;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);//error//
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(CONTENT[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
/*
#Override
public CharSequence getPageTitle(int position) {
return ImageFragmentAdapter.CONTENT[position % CONTENT.length];
}
*/
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
I use DetailsFragment.java to populate the View pager onto fragment_details.xml
public class DetailsFragment extends SherlockFragment
{
public static final String TAG = "detailsFragment";
ImageFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
//container.removeAllViews();
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_details, container,
false);
mAdapter = new ImageFragmentAdapter(getActivity().getSupportFragmentManager());
mPager = (ViewPager) view.findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
return view;
}
}
fragment_details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip" />
</LinearLayout>

Categories

Resources