Android viewpager activity problems - android

I've been working on an Android activity which contains a ViewPager with 10 images on it and an Image View below which will display the image of the ViewPager upon click.
When I try to run it after entering through my login screen, the deal crashes.
I'm not sure where are the errors LogCat warns about so if you could help me out I'd be very grateful.
Here are the LogCat messages:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.logger.SecondActivity$MyPagerAdapter.setPrimaryItem (SecondActivity.java:80)
at android.support.v4.view.ViewPager.populate (ViewPager.java:1066)
at android.support.v4.view.ViewPager.populate (ViewPager.java:914)
at android.support.v4.view.ViewPager.onMeasure (ViewPager.java:1436)
at android.view.View.measure (View.java:15848)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure (RelativeLayout.java:477)
at android.view.View.measure (View.java:15848)
at android.view.ViewGroup.measureChildWithMargins (ViewGroup.java:5012)
at com.android.internal.widget.ActionBarOverLayout.onMeasure(ActionBarOverLayout.java:302)
at android.view.View.measure (View.java:15848)
at android.view.ViewGroup.measureChildWithMargins (ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure (FrameLayout.java:310)
at android.view.View.measure (View.java:15848)
SecondActivity.java
package com.example.logger;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.view.ViewGroup;
public class SecondActivity extends Activity {
private static final int NUM_PAGES = 10;
private ViewPager mpager;
private MyPagerAdapter mPagerAdapter;
private int [] pics = {R.drawable.android_interfaz_layout_estructura_final, R.drawable.baixa, R.drawable.baixada, R.drawable.greenprogressbar,
R.drawable.layout_keyboard, R.drawable.linerlay, R.drawable.merge1, R.drawable.o2zds, R.drawable.regbd,
R.drawable.s7qrs};
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mPagerAdapter = new MyPagerAdapter(null);
mpager = (ViewPager) findViewById(R.id.viewer);
mpager.setAdapter (mPagerAdapter);
}
public void showImage (int position, View view)
{
//View is your view that you returned from instantiateItem
//and position is it's position in array you can get the image resource id
//using this position and set it to the ImageView
}
private class MyPagerAdapter extends PagerAdapter
{
SecondActivity activity;
public MyPagerAdapter (SecondActivity activity){
this.activity=activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pics.length;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public Object instantiateItem(View collection, int position) {
ImageView view = new ImageView (SecondActivity.this);
view.setImageResource (pics[position]);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void setPrimaryItem (ViewGroup container, int position, Object object)
{
super.setPrimaryItem (container, position, object);
activity.showImage(position,(View)object);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
private OnClickListener mPageClickListener = new OnClickListener()
{
public void onClick (View v)
{
// TODO Auto-generated method stub
//aquí anirà la funció per traslladar la image de la gallery a la pantalla
Integer picId = (Integer) v.getTag();
mpager.setVisibility(View.VISIBLE);
mpager.setCurrentItem(v.getId());
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
};
}
End SecondActivity.java
Activity_Second.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: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=".SecondActivity" >
<android.support.v4.view.ViewPager
android:padding="16dp"
android:id="#+id/viewer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="0.30"
/>
<ImageView
android:id="#+id/big_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="#+id/viewer"
android:layout_weight="0.70"
/>
</RelativeLayout>
End Activity_Second.xml
Just in case I'll add the MainActivity as well.
Main_Activity.java
package com.example.logger;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
attachHandlers();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void attachHandlers() {
findViewById(R.id.login).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
if(arg0.getId() == R.id.login)
{
Intent i = new Intent(this, SecondActivity.class);
startActivity(i);
}
}
}
End MainActivity.java
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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="#+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Login"
android:layout_alignParentBottom="true"
android:background="#drawable/shapes"
android:textColor="#color/text"
/>
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/input_u"
android:layout_marginTop="10dp"
android:textColor="#color/text"
/>
<EditText
android:id="#+id/password"
android:layout_below="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/input_p"
android:layout_marginTop="10dp"
android:textColor="#color/text"
/>
</RelativeLayout>
End Activity_Main.xml
I'd be very grateful if I could receive some insight into how to fix these problems.
Yours sincerely,
Mauro.

Change this
mPagerAdapter = new MyPagerAdapter(null)
to
mPagerAdapter = new MyPagerAdapter(SecondActivity.this)
The constructor looks like
public MyPagerAdapter (SecondActivity activity){
this.activity=activity; //activity is null
}
Most likely line 80 in SecondActivity.java is activity.showImage(position,(View)object); and activity is null.
Change your Pageradapter code
class MyPagerAdapter extends PagerAdapter{
MyPagerAdapter (Context context) {
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public int getCount() {
return pics.length;
}
#Override
public Object instantiateItem(View collection, int position) {
ImageView iv = new ImageView(SecondActivity.this);
((ViewPager) collection).addView(iv, 0);
iv.setImageResource(pics[position]);
return iv;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}

You are getting nullpointer error because of not getting the context of the activity in your MyPagerAdapter class
Change your initialization in your SecondActivity for the adapter as below:"
Instead of this
mPagerAdapter = new MyPagerAdapter(null);
Do this
mPagerAdapter = new MyPagerAdapter(SecondActivity.this)

it is working now
public class SecondActivity extends Activity {
private static final int NUM_PAGES = 10;
private ViewPager mpager;
private MyPagerAdapter mPagerAdapter;
private int[] pics = { R.drawable.flower1, R.drawable.flower10,
R.drawable.flower11, R.drawable.flower13, R.drawable.flower2,
R.drawable.flower6, R.drawable.flower8, R.drawable.flower7,
R.drawable.image3, R.drawable.flower3 };
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mPagerAdapter = new MyPagerAdapter(this,pics);
mpager = (ViewPager) findViewById(R.id.viewer);
mpager.setAdapter(mPagerAdapter);
}
public void showImage(int position, View view) {
// View is your view that you returned from instantiateItem
// and position is it's position in array you can get the image resource
// id
// using this position and set it to the ImageView
}
private class MyPagerAdapter extends PagerAdapter {
Activity activity;
int imageArray[];
public MyPagerAdapter(SecondActivity 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);
System.out.println(position);
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;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.second, menu);
return true;
}
private OnClickListener mPageClickListener = new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// aquí anirà la funció per traslladar la image de la gallery a la
// pantalla
Integer picId = (Integer) v.getTag();
mpager.setVisibility(View.VISIBLE);
mpager.setCurrentItem(v.getId());
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
};
}

Related

how to set images into the viewpager from horizontalscrollview in android

i am trying to set images into the viewpager from horizontalscrollview.
i can not get the id of the horizontalscrollview to use in setcurrentItem method.
i have tried so many things but i could not.
Here is the MainActivity class
public class MainActivity extends AppCompatActivity {
int toplamSayfa = 5;
private View btnNext, btnPrev;
HorizontalScrollView hs;
ImageView imageView = null;
private Integer images[] = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e};
ViewPager viewPager;
LinearLayout myGallery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomPagerAdapter adapter = new CustomPagerAdapter(this, toplamSayfa);
myGallery = (LinearLayout) findViewById(R.id.container);
hs = (HorizontalScrollView) findViewById(R.id.scrollview);
viewPager = (ViewPager) findViewById(R.id.view_pager);
btnNext = findViewById(R.id.next);
btnPrev = findViewById(R.id.prev);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
btnPrev.setOnClickListener(onClickListener(0));
btnNext.setOnClickListener(onClickListener(1));
addImagesToThegallery();
}
private void addImagesToThegallery() {
final LinearLayout imageGallery = (LinearLayout) findViewById(R.id.container);
for ( Integer image : images) {
imageGallery.addView(getImageView(image));
}
}
private View getImageView(final Integer image) {
imageView = new ImageView(getApplicationContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 10, 0);
imageView.setLayoutParams(lp);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//the method where i am stuck
viewPager.setCurrentItem();
}
});
imageView.setImageResource(image);
return imageView;
}
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i > 0) {
if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount() - 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
} else {
if (viewPager.getCurrentItem() > 0) {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
}
};
}
}
Update the addImagesToThegallery method to keep the index of the image while adding the image to gallery from your images array :
private void addImagesToThegallery() {
final LinearLayout imageGallery = (LinearLayout) findViewById(R.id.container);
int i = 0;
for ( Integer image : images) {
imageGallery.addView(getImageView(image,i));
i += 1;
}
}
and use the index here :
private View getImageView(final Integer image, int index) {
imageView = new ImageView(getApplicationContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 10, 0);
imageView.setLayoutParams(lp);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//use the index here
viewPager.setCurrentItem(index);
}
});
imageView.setImageResource(image);
return imageView;
}
try this , but ignore the if-else part:
package com.example.hotel_app_regularuser;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class PageTwo extends Activity {
ViewPager vpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_two);
vpager=(ViewPager)findViewById(R.id.viewPager);
PagerAdapter adapter = new customAdapter(PageTwo.this);
vpager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.page_two, menu);
return true;
}
}
class customAdapter extends PagerAdapter
{
Context context;
int imageId[]={
R.drawable.chinese,
R.drawable.euro,
R.drawable.americanfood,
R.drawable.continental
};
public customAdapter(Context context)
{
this.context=context;
}
#Override
public Object instantiateItem(ViewGroup container,int position)
{
Typeface type = Typeface.createFromAsset(this.context.getAssets(), "fonts/Confetti.ttf");
LayoutInflater inflater=((Activity)context).getLayoutInflater();
View viewitem=inflater.inflate(R.layout.activity_page_two,container,false);
ImageView im=(ImageView)viewitem.findViewById(R.id.imageView1);
im.setImageResource(imageId[position]);
TextView textView1 = (TextView) viewitem.findViewById(R.id.textView1);
if(position==0)
{
textView1.setText("Chinese");
}
if(position==1)
{
textView1.setText("European");
}
if(position==2)
{
textView1.setText("American");
}
if(position==3)
{
textView1.setText("Continental");
}
textView1.setTypeface(type);
textView1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 70);
textView1.setTextColor(Color.RED);
((ViewPager)container).addView(viewitem);
return viewitem;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return imageId.length;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0==((View)arg1);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
((ViewPager) container).removeView((View) object);
}
}
To create a scroll view, try this xml file:
<!--
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=".Check_Availability"
android:stretchColumns="0,1"
android:id="#+id/main_table"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</TableLayout>
-->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout android:id="#+id/main_table"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow android:id="#+id/header"/>
</TableLayout>
</ScrollView>
Note that the commented out section id for a page that used table layout. Hope this can help!

adding next and previous buttons to ViewPager

I want to make an image slider with Android Studio.
I found a new slider code, built with ViewPager, I tried it and worked..
but I want to add 2 buttons for next and previous..
When clicked button, it must go to next picture or previous picture.
here the mainactivity,
package org.trial.slider;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
}
ImageAdapter.java file,
package org.trial.slider;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
/**
* Created by ismail on 30.03.16.
*/
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
And I have 2 XML files; fragment_pager and swipe_fragment
add button your MainActivity and activity_main.xml
add code button.setonclicklister(this); in OnCreate()
Example code here :
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
//prev button
case R.id.btn_list_detail_img_prev:
viewPager.setCurrentItem(mPager.getCurrentItem()-1,true);
break;
//nextbutton, 1st argument : pageindex, 2nd argument : Enable smooth
case R.id.btn_list_detail_img_next:
viewPager.setCurrentItem(mPager.getCurrentItem()+1,true);
break;
}
There is a method name viewPager.setCurrentItem(position).
This method take a integer value as a index and is set on viewPager object using this method you can change the position if pager item.
class MyClass extends Fragment implements ViewPager.OnPageChangeListener {
private int selectedViewPager = 0;
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.backward:
if (selectedViewPager > 0) {
viewPager.setCurrentItem(selectedViewPager - 1, true);
}
break;
case R.id.fwd:
if (viewPager.getAdapter().getCount() > selectedViewPager) {
viewPager.setCurrentItem(selectedViewPager + 1, true);
}
break;
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
selectedViewPager = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
}

How can I manually set icons for each fragments in navigation drawer recycler view?

I followed android hive tutorials to make this navigation drawer. This is my code,
MainActivity.Java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import androidhive.info.materialdesign.AddNewBiller;
import androidhive.info.materialdesign.R;
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
int ICONS[] = {R.drawable.ic_dashboard,R.drawable.ic_action,R.drawable.ic_quick};
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_add) {
startActivity(new Intent(this, AddNewBiller.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
FragmentDrawer
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import androidhive.info.materialdesign.R;
import androidhive.info.materialdesign.adapter.NavigationDrawerAdapter;
import androidhive.info.materialdesign.model.NavDrawerItem;
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
NavigationDrawerAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
import androidhive.info.materialdesign.R;
import androidhive.info.materialdesign.model.NavDrawerItem;
/**
* Created by Ravi Tamada on 12-03-2015.
*/
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
}
}
}
Layout file- fragment_navigation_drawer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/navigationBarColor">
<RelativeLayout
android:id="#+id/nav_header_container"
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_alignParentTop="true"
android:background="#android:color/white">
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:src="#drawable/ic_profile"
android:scaleType="fitCenter"
android:id="#+id/imageView2"
android:layout_above="#+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:background="#drawable/logo"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Username"
android:textColor="#color/colorPrimaryDark"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imageView2"
android:layout_toEndOf="#+id/imageView2"
android:textStyle="italic"
android:textSize="#dimen/abc_text_size_small_material" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/nav_header_container"
android:layout_marginTop="15dp"
android:divider="#FFFFFF"
android:dividerHeight="1dp"
/>
</RelativeLayout>
When I try to change them it is making changes for all the fragments. Also it would be great if any of you could help me with adding separators in between each fragments.
you have not set any images for the imageView present in your nav_drawer_row.xml file. Make sure you are setting image in onBindViewHolder method.

Minor bug with ViewPager and PhotoViewAttacher

Minor bug with ViewPager and PhotoViewAttacher, the second and following pictures are displayed at the top first, and only then click the center stand. How to make that picture was in the center?
TestPager.java
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.squareup.picasso.Picasso;
import uk.co.senab.photoview.PhotoViewAttacher;
public class TestPager extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_pager);
CustomPagerAdapter mCustomPagerAdapter = new CustomPagerAdapter(this);
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCustomPagerAdapter);
}
#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);
}
class CustomPagerAdapter extends PagerAdapter {
Picasso mPicasso;
PhotoViewAttacher mAttacher;
int[] mResources = {
R.drawable.first,
R.drawable.second,
R.drawable.third
};
Context mContext;
LayoutInflater mLayoutInflater;
public CustomPagerAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mResources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageViewPager);
mPicasso.with(TestPager.this).load(mResources[position]).into(imageView);
container.addView(itemView);
mAttacher = new PhotoViewAttacher(imageView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
}
layout_pager.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:paddingBottom="#dimen/activity_vertical_margin"
android:id="#+id/relativeLayout">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</RelativeLayout>
pager_item.xml
<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:layout_centerInParent="true"
android:id="#+id/imageViewPager" />
</LinearLayout>
I used UniversalImageLoader instead of Picasso and met the same problem.
My solution is to new the attacher in the async loading callback.
In my case the code is:
imageLoader.displayImage(url, imgView, new ImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// Make imageview interactive
attacher = new PhotoViewAttacher(imgView);
}
});
For your case using Picasso, it may be like:
mPicasso.with(TestPager.this).load(mResources[position]).into(imageView, new Callback() {
#Override
public void onSuccess() {
mAttacher = new PhotoViewAttacher(imageView)
}
#Override
public void onError() {
}
});

Error in the ViewPager

I use PagerView in my application. But I have mistake. I load image in each pages. On all pages I see my images. but the page that has a position 0 in pagerAdapter is empty always. What I do not correctly?
public class MainActivity extends ActionBarActivity {
String TAG = "State";
static ViewPager pager;
static PagerAdapter pagerAdapter;
public static MainActivity activity;
static final int PAGE_COUNT = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
pager = (ViewPager) findViewById(R.id.pager);
pager.setOffscreenPageLimit(0);
final ArrayList<String> imagePaths = new ArrayList<String>();
imagePaths.add("http://tlt.ru/uploads/2014/05/94e1e91067997356912d68e0acc36d31_x240.jpg");
imagePaths.add("http://tlt.ru/uploads/2014/05/d2cb96bd2e26fd19c4ec5a125d8a6ada_x240.jpg");
imagePaths.add("http://tlt.ru/uploads/2014/05/6bc17baed9ef08a7aa1c68db2dcd650c_x240.jpg");
pagerAdapter = new FullScreenImageAdapter(activity, imagePaths);
pager.setAdapter(pagerAdapter);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//Log.d(TAG, "onPageSelected, position = " + position);
// update();
FullScreenImageAdapter.startRefresh(imagePaths.get(position));
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
pager.setCurrentItem(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static void update() {
// pager.setAdapter(pagerAdapter);
// refreshView(pager.getCurrentItem());
pagerAdapter.notifyDataSetChanged();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
public static TouchImageView imgDisplay;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.fragment, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imageView1);
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Refresh mt = new Refresh();
try {
mt.execute(new URL(_imagePaths.get(position)));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 300);
// imgDisplay.setImageBitmap(bitmap);
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
public static void startRefresh(final String url) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Refresh mt = new Refresh();
try {
mt.execute(new URL(url));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
How I can load image in page[0]?
I thikn the problem is in the getItemPosition, try this:
#Override
public int getItemPosition (Object object){
int index = _imagePaths.indexOf(object);
if (index == -1)
return POSITION_NONE;
else
return index;
}
The problem is with the position, you can find a better solution for pager here. You need to Modify activity_main.xml to include android.support.v4.view.ViewPager in layout.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<android.support.v4.view.ViewPager
android:id="#+id/myviewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
And MainActivity.java
package com.example.androidviewpagerapp;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
public class MainActivity extends Activity {
ViewPager viewPager;
MyPagerAdapter myPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.myviewpager);
myPagerAdapter = new MyPagerAdapter();
viewPager.setAdapter(myPagerAdapter);
}
private class MyPagerAdapter extends PagerAdapter{
int NumberOfPages = 5;
int[] res = {
android.R.drawable.ic_dialog_alert,
android.R.drawable.ic_menu_camera,
android.R.drawable.ic_menu_compass,
android.R.drawable.ic_menu_directions,
android.R.drawable.ic_menu_gallery};
int[] backgroundcolor = {
0xFF101010,
0xFF202020,
0xFF303030,
0xFF404040,
0xFF505050};
#Override
public int getCount() {
return NumberOfPages;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView textView = new TextView(MainActivity.this);
textView.setTextColor(Color.WHITE);
textView.setTextSize(30);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setText(String.valueOf(position));
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(res[position]);
LayoutParams imageParams = new LayoutParams(
LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(imageParams);
LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
LayoutParams layoutParams = new LayoutParams(
LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
layout.setBackgroundColor(backgroundcolor[position]);
layout.setLayoutParams(layoutParams);
layout.addView(textView);
layout.addView(imageView);
final int page = position;
layout.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"Page " + page + " clicked",
Toast.LENGTH_LONG).show();
}});
container.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
}

Categories

Resources