I created a customViewPager class to block swiping between the tabs.Swiping has been disabled but the UI components inside the tabs are not being displayed.
Here is the CustomViewPager.java file.
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs){
super(context,attrs);
this.enabled = true;
}
public CustomViewPager(Context context){
super(context);
this.enabled = true;
}
#Override
public boolean onTouchEvent(MotionEvent event){
if(this.enabled){
return super.onTouchEvent(event);
}
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event){
if(this.enabled){
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled){
this.enabled = enabled;
}
}
Here is the MainActivity.java file
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener{
private TabLayout tabLayout;
public static int swipe = 0;
private CustomViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (CustomViewPager)findViewById(R.id.mViewPager);
Pager adapter= new
Pager(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Here is Tab1.java file
package com.example.nitesh.finaltab;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by Nitesh on 2/6/2017.
*/
public class Tab1 extends Fragment {
int click = 0;
View view;
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
view = inflater.inflate(R.layout.tab1, container, false);
button = (Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Button is clicked","Tab1");
if(click == 0){
MainActivity.swipe = 1;
click = 1;
}
else if(click == 1){
MainActivity.swipe = 0;
click = 0;
}
}
});
return view;
}
}
Here is the activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.nitesh.finaltab.MainActivity">
<!-- our toolbar -->
<android.support.v7.widget.Toolbar
android:id = "#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight = "?attr/actionBarSize"
/>
<android.support.design.widget.TabLayout
android:id = "#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<!-- View pager to swipe views -->`
<com.example.nitesh.finaltab.CustomViewPager
android:layout_width="0dp"
android:id="#+id/mViewPager"
android:layout_height="0dp">
</com.example.nitesh.finaltab.CustomViewPager>
</LinearLayout>
Am seeing just an empty Tab on selecting tab1. Please point out the mistake which i am doing.
Related
I have been searching a lot of tutorials to implement an on item long press Listener on a Listview which is Inside a RecyclerView. So far I had no luck.
I want a menu to more ap after holding the List Item for some time. I am attaching my code here please help me with it.
I have added my complete code Including the MainAcyivity.
I have a tabbed view which contains 3tabs. Inside the tab view, there is a fragment which contains a Listview.
I want the List to be long pressed to bring a popup menu which has as add or delete options.
MainActivity.java
package tabbardemo.com.materialdesigntabs_demo;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static Toolbar toolbar;
private static ViewPager viewPager;
private static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);//setting tab over viewpager
//Implementing tab selected listener over tablayout
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
Log.e("TAG","TAB1");
break;
case 1:
Log.e("TAG","TAB2");
break;
case 2:
Log.e("TAG","TAB3");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
//Setting View Pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment("Inbox"), "Inbox");
adapter.addFrag(new EventsFragment("QA"), "QA");
adapter.addFrag(new EventsFragment("Events"), "Events");
viewPager.setAdapter(adapter);
}
//View Pager fragments setting adapter class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();//fragment arraylist
private final List<String> mFragmentTitleList = new ArrayList<>();//title arraylist
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
//adding fragments and title method
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
activity_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinatorLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- AppBar Layout -->
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="fill_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<!-- Tab Layout for creating tabs -->
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<!-- Helps handing the Fragments for each Tab -->
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
dummy_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/blue"
android:gravity="center"
android:orientation="vertical">
<!-- Recycler View -->
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none" />
</LinearLayout>
DummyFragment.java
package tabbardemo.com.materialdesigntabs_demo;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* Created by SONU on 16/09/15.
*/
public class DummyFragment extends Fragment {
private View view;
private String title;//String for tab title
private static RecyclerView recyclerView;
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
public void onLongItemClick(View view, int position);
}
public DummyFragment(String title) {
this.title = title;//Setting tab title
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.dummy_fragment, container, false);
setRecyclerView();
return view;
}
//Setting recycler view
private void setRecyclerView() {
recyclerView = (RecyclerView) view
.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView
.setLayoutManager(new LinearLayoutManager(getActivity()));//Linear Items
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
arrayList.add(title+" Items " + i);//Adding items to recycler view
}
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList);
recyclerView.setAdapter(adapter);// set adapter on recyclerview
}
}
RecyclerView_Adapter
package tabbardemo.com.materialdesigntabs_demo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* Created by SONU on 10/09/15.
*/
public class RecyclerView_Adapter extends
RecyclerView.Adapter<DemoViewHolder> {
private ArrayList<String> arrayList;
private Context context;
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public RecyclerView_Adapter(Context context,
ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getItemCount() {
return (null != arrayList ? arrayList.size() : 0);
}
#Override
public void onBindViewHolder(DemoViewHolder holder,
int position) {
final DemoViewHolder mainHolder = (DemoViewHolder) holder;
//Setting text over textview
// mainHolder.bind(arrayList.get(position), listener);
mainHolder.title.setText(arrayList.get(position));
}
#Override
public DemoViewHolder onCreateViewHolder(
ViewGroup viewGroup, int viewType) {
LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());
ViewGroup mainGroup = (ViewGroup) mInflater.inflate(
R.layout.item_row, viewGroup, false);
DemoViewHolder mainHolder = new DemoViewHolder(mainGroup) {
#Override
public String toString() {
return super.toString();
}
};
// 13805 ////////////////////////////////
return mainHolder;
}
}
DemoViewHolder.java
package tabbardemo.com.materialdesigntabs_demo;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by SONU on 31/08/15.
*/
public abstract class DemoViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public DemoViewHolder(View view) {
super(view);
this.title = (TextView) view.findViewById(R.id.cardTitle);
}
}
ite_row.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/iv_image"
android:padding="10dp"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:src="#mipmap/ic_launcher">
</ImageView>
<TextView
android:id="#+id/cardTitle"
android:layout_toRightOf ="#+id/iv_image"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:padding="15dp"
android:text="Card Title"
android:textColor="#000000"
android:textSize="17sp" ></TextView>
</RelativeLayout>
1- create your menu items (your list item to show on long click)
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/one"
android:title="One"/>
<item
android:id="#+id/two"
android:title="Two"/>
<item
android:id="#+id/three"
android:title="Three"/>
</menu>
2- setup listener and menu.
#Override
public void onBindViewHolder(DemoViewHolder holder, int position) {
holder.title.setText(arrayList.get(position));
holder.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showMenu(v);
return true;
}
});
}
// method to open a popup menu(list) upon long click in the recyclerView item
private void showMenu(View view){
PopupMenu popup = new PopupMenu(context,view );
popup.getMenuInflater()
.inflate(R.menu.popup_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
return true;
}
});
popup.show();
}
When you are doing setOnItemLongClickListener() in the ListView:
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// Dialog/Popup will appears here
showAddDeleteDialog();
return true;
}
});
public void showAddDeleteDialog(){
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Add or Delete Dialog");
// dialog.setMessage("Are you sure you want to delete this entry?" );
dialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Action for "Add".
}
})
.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Action for "Delete".
}
});
final AlertDialog alert = dialog.create();
alert.show();
}
In my activity (Please see image), I have seek bar and view pager ( have 3 pages).
I want so that, when seek bar in activity change, the text of the fragment size also varies.
How can I do it?
I try it with interface but it not run.
Mainactivity
package com.creativei.viewpagerloop;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private static final String LOG_TAG = "ViewPagerLoop";
public static final String[] content = new String[] {
"Hello Welcome to ViewPager Loop Example. This is first view. Swipe right → for second view, swipe left � for last view.",
"Awesome, now you are on second view. Swipe right → again to go to last view.",
"Finally made it to last view, swipe right → again to go to first view." };
Interface inter;
public MainActivity(Interface inter) {
this.inter = inter;
}
private SeekBar seekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
TextView counter = (TextView) findViewById(R.id.counter);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
inter.seekBarChange(progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
SimpleViewPagerAdapter adapter = new SimpleViewPagerAdapter(
getSupportFragmentManager(), pager, content, counter);
pager.setAdapter(adapter);
pager.setOnPageChangeListener(adapter);
pager.setCurrentItem(1, false);
}
public static class SimpleFragment extends Fragment implements Interface {
private TextView textView;
public SimpleFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
String content = getArguments().getString("content");
textView = (TextView) rootView.findViewById(R.id.content);
textView.setText(content);
return rootView;
}
#Override
public void seekBarChange(int id) {
// TODO Auto-generated method stub
textView.setTextSize(id);
}
}
public static class SimpleViewPagerAdapter extends
FragmentStatePagerAdapter implements OnPageChangeListener {
private String[] content;
private ViewPager pager;
private TextView counter;
public SimpleViewPagerAdapter(FragmentManager fm, ViewPager pager,
String[] content, TextView counter) {
super(fm);
this.pager = pager;
this.content = content;
this.counter = counter;
}
#Override
public Fragment getItem(int position) {
SimpleFragment fragment = new SimpleFragment();
Bundle bundle = new Bundle();
int index = position;
bundle.putString("content", content[index]);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return content.length;
}
#Override
public void onPageSelected(int position) {
}
private String makeCounterText(int pageNo) {
return "Page " + pageNo + " of " + content.length;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
}
}
Interface
package com.creativei.viewpagerloop;
public interface Interface {
public void seekBarChange(int id);
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.creativei.viewpagerloop.MainActivity"
tools:ignore="MergeRootFrame" >
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/counter"
android:layout_below="#+id/seekBar1" />
<TextView
android:id="#+id/counter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:gravity="center_horizontal" />
</RelativeLayout>
fragment_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"
tools:context="com.creativei.viewpagerloop.SimpleFragment" >
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
You can get reference from this example http://sampleprogramz.com/android/seekbar.php
Initially my ViewPager takes list and set view accordingly. But if the end of ViewPager or start of ViewPager is reached I want to add more view to ViewPager and set positions accordingly, how can I accomplish this by writing an efficient code?
This is my Adapter
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Declare Variables
TouchImageView image;
ImageEntity entity=list.get(position);
final TextView text;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,false);
// Locate the TextViews in viewpager_item.xml
image = (TouchImageView) itemView.findViewById(R.id.imageView1);
View progress=itemView.findViewById(R.id.progress);
text=(TextView) itemView.findViewById(R.id.text);
text.setVisibility(View.INVISIBLE);
text.setText(entity.message);
makeTextViewResizable(text, 1, "View more", true);
// Capture position and set to the TextViews
image.setImageURI(Uri.parse(Constants.FLDR_IMG+entity.localImageName));
ContextCommons.loadMainImage(context, entity, progress, image);
// Add viewpager_item.xml to ViewPager
container.addView(itemView);
return itemView;
}`
This is custom ViewPager
public class CustomViewPager extends ViewPager{
float mStartDragX;
float x = 0;
OnSwipeOutListener mOnSwipeOutListener;
static final String TAG="CustomViewPager";
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setOnSwipeOutListener(OnSwipeOutListener listener) {
mOnSwipeOutListener = listener;
}
private void onSwipeOutAtStart() {
if (mOnSwipeOutListener!=null) {
mOnSwipeOutListener.onSwipeOutAtStart();
}
}
private void onSwipeOutAtEnd() {
if (mOnSwipeOutListener!=null) {
mOnSwipeOutListener.onSwipeOutAtEnd();
}
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch(ev.getAction() & MotionEventCompat.ACTION_MASK){
case MotionEvent.ACTION_DOWN:
mStartDragX = ev.getX();
break;
}
return super.onInterceptTouchEvent(ev);
}
#Override
public boolean onTouchEvent(MotionEvent ev){
if(getCurrentItem()==0 || getCurrentItem()==getAdapter().getCount()-1){
final int action = ev.getAction();
float x = ev.getX();
switch(action & MotionEventCompat.ACTION_MASK){
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
if (getCurrentItem()==0 && x>mStartDragX) {
/here i want to update ArrayList from start which is supplied to view adapter/
ImageActivity.loadStart();
}
if (getCurrentItem()==getAdapter().getCount()-1 && x<mStartDragX){
//here i want to update Arraylist from bottom which is supplied to view adapter
ImageActivity.loadEnd();
}
break;
}
}else{
mStartDragX=0;
}
return super.onTouchEvent(ev);
}
public interface OnSwipeOutListener {
void onSwipeOutAtStart();
void onSwipeOutAtEnd();
}
}
So I need to update list which is supplied to ViewPager to add dynamic view when ViewPager reaches the end or start.
I am adding view like this which I think is a wrong approach
public static void loadStart(){
ArrayList<ImageEntity> image = null;
try {
ContextCommons.loadImages(context, Constants.DIRECTION_TOP, list.get(0).id);
image= SelectQueries.getTopLocalImagesOnId(context, list.get(0).id, Constants.DIRECTION_TOP);
list.addAll(0,image);
} catch (Exception e) {
e.printStackTrace();
}
viewPager.getAdapter().notifyDataSetChanged();
viewPager.setCurrentItem(image.size()-1);
}
I have made some editis to Googles viewPager example to keep it simple,
by clicking the button on fragment you can easily increase the pages to View Pager.
This is a demo I showed here how to notify anychanges as you wish to increase pages. you will have to make your own custom Adapter and list of pages to keep pages and it's position in check...
I am sorry, I would not be witting entire code :(
Make a fragment with following xml and code...
<LinearLayout 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:gravity="center"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_blank_fragment" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button" />
</LinearLayout>
and it's code is
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class MyFragment extends Fragment {
private Button button;
private TextView textView;
private static AddPage test;
public MyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_my, container, false);
button = (Button) layout.findViewById(R.id.button);
return layout;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
test.addAnotherPage();
}
});
}
public void setAddPage(AddPage addPage) {
test = addPage;
}
public interface AddPage {
void addAnotherPage();
}
}
Main Activity xml
<LinearLayout 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"
tools:context=".AddingPagesTest">
<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" />
</LinearLayout>
Activities Code
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class AddingPagesTest extends AppCompatActivity {
public static int NUM_PAGES = 2;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
private MyFragment set;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_pages_test);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#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_adding_pages_test, menu);
return true;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter implements MyFragment.AddPage {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
MyFragment myFragment = new MyFragment();
myFragment.setAddPage(this);
return myFragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
#Override
public void addAnotherPage() {
NUM_PAGES++;
mPagerAdapter.notifyDataSetChanged();
}
}
}
I have an application page with viewpager containing two fragments.
When my activity pops up , a server request is made for loading current data and then adapter is set.
But the app crashes with the following error.
Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setMenuVisibility(boolean)' on a null object reference
While debugging, viewPager.setAdapter(adapter) showed null pointer exception. Neither my viewPager is null nor my Adapter.
I am not able to figure out why this is happening.
Please help!!
Thanks in advance!!
Found the problem.. In my fragmentPagerAdapter, getItem() was returning null for a fragment.
Try this code
create a class file TabOne.java
package com.example.tabfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_one, null);
return rootView;
}
}
create a class file TabTwo.java
package com.example.tabfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_two, null);
return rootView;
}
}
**create xml file tab_one.xml and tab_two.xml **
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="#string/tab_2" />
</RelativeLayout>
Create a class TabFragmentPageAdapter.java
package com.example.tabfragment;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabFragmentPageAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;
public TabFragmentPageAdapter(FragmentManager fm, List<Fragment> fragments,
Bundle args) {
super(fm);
this.fragments = fragments;
this.args = args;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Create a classs file TabFragments.java
public class TabFragments extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
public static final int TAB_LOGIN = 0;
public static final int TAB_REG = 1;
private TabHost tabHost;
private int currentTab = TAB_LOGIN;
private ViewPager viewPager;
private TabFragmentPageAdapter pageAdapter;
private List<Fragment> fragments;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, null);
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setOnPageChangeListener(this);
fragments = new ArrayList<Fragment>();
fragments.add(new TabOne());
fragments.add(new TabTwo());
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
pageAdapter = new TabFragmentPageAdapter(getChildFragmentManager(),
fragments, getArguments());
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.tab_1));
tabHost.addTab(newTab(R.string.tab_2));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.parseColor("#304c58"));
// tabHost.setBackgroundResource(R.drawable.tab_selector);
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final View textView = view.findViewById(android.R.id.title);
((TextView) textView).setTextColor(Color.parseColor("#e2ebf0"));
((TextView) textView).setSingleLine(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
tabHost.getTabWidget().getChildAt(i)
.findViewById(android.R.id.icon);
tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 75;
} else {
if (view != null) {
// reduce height of the tab
view.getLayoutParams().height *= 0.77;
if (textView instanceof TextView) {
((TextView) textView).setGravity(Gravity.CENTER);
textView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
}
}
}
tabHost.setOnTabChangedListener(TabFragments.this);
tabHost.setCurrentTab(currentTab);
}
private TabSpec newTab(int titleId) {
TabSpec tabSpec = tabHost.newTabSpec(getString(titleId));
tabSpec.setIndicator(getString(titleId));
tabSpec.setContent(new TabFactory(getActivity()));
return tabSpec;
}
#Override
public void onPageScrollStateChanged(int position) {
}
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
updateTab();
}
#SuppressWarnings("unused")
private void updateTab() {
switch (currentTab) {
case TAB_LOGIN:
TabOne login = (TabOne) fragments.get(currentTab);
break;
case TAB_REG:
TabTwo register = (TabTwo) fragments
.get(currentTab);
break;
}
}
class TabFactory implements TabContentFactory {
private final Context context;
public TabFactory(Context context) {
this.context = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(context);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
}
Create you activity class
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.v7.app.ActionBarActivity;
import android.util.Log;
public class MainActivity extends ActionBarActivity {
Fragment fragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment = new TabFragments();
Log.i("fragment", "" + fragment.getId());
if (fragment != null) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.frame_container, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
}
}
Create mainactivity.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.DrawerLayout>
create tab fragment_home.xml file
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ts="http://schemas.android.com/apk/res-auto"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fadingEdge="none"
android:background="#394c58"
android:tabStripEnabled="false" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
</TabHost>
I have fragment activity that have view pager, I want every changing page the content is change programmatically. `
package com.idroid.splashscreen;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class ScreenSlidePagerActivity extends FragmentActivity {
private static final int NUM_PAGES = 5;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
OnPageChangeListener pageChangeListener=null;
pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
Toast.makeText(getApplicationContext()
.getApplicationContext(),
"page "+position,
Toast.LENGTH_LONG).show();
TextView txt=(TextView) findViewById(R.id.txtcoba);
txt.setText("page "+position);
}
};
mPager.setOnPageChangeListener(pageChangeListener);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new ScreenSlidePageFragment();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
`
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtcoba"
style="?android:textAppearanceMedium"
android:padding="16dp"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="coba" />
</ScrollView>
I change it on page selected method and change the content of text view. for the toast it's work but for the text doesn't change. but on page 4 when I back to page 3, the page 3 show the page. but the other page not.
what should I do ? thanks before. this is the ScreenSlidePageFragment class
package com.idroid.splashscreen;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_screen_slide_page, container, false);
return rootView;
}
}
this is fragment_screen_slide_page.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtcoba"
style="?android:textAppearanceMedium"
android:padding="16dp"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="coba" />
</ScrollView>
this is activity_screen_slide.xml
<?xml version="1.0" encoding="utf-8"?>
<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" />
Issue is your trying to set the TextView of Fragment layout.
As per your code your TextView is in the ScreenSlidePageFragment layout.
Remove the 'TextView' setText in onPageeSelcted
Change your ScreenSlidePageFragment like this
private class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View row = inflater.inflate(R.layout.activity_screen_slide, container, false);
TextView txt=(TextView) row.findViewById(R.id.txtcoba);
txt.setText("page using fragment");
return row;
}
}