I have created A layout and I dynamically add tabs according to data I receive. I do the same with fragments updating the Text View dynamically. Although when the layout loads and if I swipe through the fragments or view pager (sorry I am new to all these hope my terminology is right) they update just okay (meaning there is sometimes lag in updating not much of an issue) and with right data. although, if in fresh I open the layout and click on tab to change my fragments I get no data or wrong data. Example:- when Layout loads for first time my first & third tab load up fine. If I click on a second Tab (not swiping but touching the tabs on top for the whole time), my second tab doesn't have any data in its fragment. On moving round here and there selecting tabs randomly first tab loads second tabs data, but second tab never loads anything. Its not the same when I swipe if I load page new or for first time.
Let me know where I am doing wrong. Thank you.
Here is my code:-
Layout file - show_score.xml
<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.lp.activity.ShowScorePassagesActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/children_school"
android:scaleType="centerCrop"
android:alpha="0.5"
android:layout_below="#+id/appBackBar"/>
<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">
<include android:id="#+id/appBackBar"
layout="#layout/detail_appbar"/>
<android.support.design.widget.TabLayout
android:id="#+id/passagetabs"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
</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>
Fragment File - fragment_show_score_passage.xml
<android.support.constraint.ConstraintLayout 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/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lp.activity.ShowScorePassagesActivity$PlaceholderFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<android.support.v7.widget.CardView
android:id="#+id/cardView4"
android:layout_width="match_parent"
android:layout_height="200dp"
app:cardElevation="5dp"
android:scaleType="fitXY"
android:layout_margin="5dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/scrollbar_shape_style">
<TextView
android:id="#+id/showScore"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="18dp"
android:scaleType="fitXY"
android:text="TextView"
android:autoLink="web"
android:linksClickable="true"
android:padding="20dp"
android:clipToPadding="false"/>
</ScrollView>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="5dp"
android:layout_below="#+id/cardView4"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/scrollbar_shape_style">
<GridView
android:id="#+id/fluencyAudioGrid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="2dp"
android:verticalSpacing="5dp"
android:columnWidth="120dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clipToPadding="false"
android:stretchMode="spacingWidthUniform"
layout="#layout/icons_for_dashboard"
android:scrollbarThumbVertical="#drawable/scroolbar_style"
android:scrollbarTrackVertical="#drawable/scroolbar_style_background">
</GridView>
</ScrollView>
</android.support.v7.widget.CardView>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
And the main Java File where the magic happens - ShowScorePassageActivity.java
public class ShowScorePassagesActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public GridView gridView;
public ArrayList<String> gridItems = new ArrayList<String>();
public static TextView fragTextView;
static String fragNewTextView = "";
public static ArrayList<String> fluencyMarksList = new ArrayList<>();
public TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_score_passages);
Intent in = getIntent();
String intentData = in.getStringExtra("intentData");
String fluencyMarks = in.getStringExtra("fluencyMarks");
tabLayout = (TabLayout) findViewById(R.id.passagetabs);
String mFluencyMarkList []= fluencyMarks.split("#");
fluencyMarksList = new ArrayList<String>(Arrays.asList(mFluencyMarkList));
int count = 1;
int counts=fluencyMarksList.size();
for(int i = 0; i < counts; i++){
tabLayout.addTab(tabLayout.newTab().setText("Passage "+count));
count=count+1;
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
mViewPager = (ViewPager) findViewById(R.id.container);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
int position = tab.getPosition();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
if (position ==0){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0), Html.FROM_HTML_MODE_COMPACT));
}
else if (position ==1){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(1) , Html.FROM_HTML_MODE_COMPACT));
}
else if (position ==2){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(2) , Html.FROM_HTML_MODE_COMPACT));
}
} else {
if (position ==0){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0)));
}
else if (position ==1){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(1)));
}
else if (position ==2){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(2)));
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
fragTextView.setText("");
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#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_show_score_passages, 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;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
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;
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_show_score_passages, container, false);
fragTextView = (TextView) rootView.findViewById(R.id.showScore);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0) , Html.FROM_HTML_MODE_COMPACT));
} else {
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0)));
}
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
int mNumOfTabs;
Fragment fragment = null;
public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs=NumOfTabs;
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
}
This is what I did:
It is only a example of what worked for me in the hopes of helping you
In OnCreate:
ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
this.addPages(mViewPager);
mViewPager.setOffscreenPageLimit(3);
TabLayout tabLayout = (TabLayout) findViewById(R.id.mTab_ID);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.addOnTabSelectedListener(listener(mViewPager));
Then add the fragments to the TabLayout by doing:
//ADD ALL PAGES TO TABLAYOUT
private void addPages(ViewPager pager) {
adapter = new MyFragPagerAdapter(getSupportFragmentManager());
adapter.addPage(new FragmentAdapter1());
adapter.addPage(new FragmentAdapter2());
adapter.addPage(new FragmentAdapter3());
//SET ADAPTER TO PAGER
pager.setAdapter(adapter);
}
Then implement TabLayout click events OnTabSelectedListener by doing:
//TabLayout Click Events
private TabLayout.OnTabSelectedListener listener(final ViewPager pager) {
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
Related
So this has been bugging me for like a week and I haven't found the answer yet.
Basically I have this MainActivity which contains the main code and a fragment that work for the listview.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Button bNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RoomServer(), "Room Server");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
RoomServer.java
public class RoomServer extends ListFragment implements OnItemClickListener{
public RoomServer() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rs, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setChoiceMode(getListView().CHOICE_MODE_MULTIPLE);
getListView().setTextFilterEnabled(true);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.rs_list, android.R.layout.simple_list_item_checked);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}
}
Fragment_rs.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.RoomServer">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
<Button
android:id="#+id/bNext_rs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
android:layout_marginRight="39dp"
android:layout_marginEnd="39dp"
android:layout_marginBottom="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
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:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_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="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
The items of listview r declared inside strings.XML
As u can see I'm using CHOICE_MODE_MULTIPLE to create checkbox in the listview. And now I'm stuck at how to get the value of this checkbox. I'm planning to use Volley to send value to my database by a button click. Most of the answer I saw was using the isChecked and stuff but I dont really understand how to implement it in my array adapter.
You can either implement a custom array adapter yourself, or use this method in the ListView class to get a SparseBooleanArray of the indexes of the selected items:
//Submit button example
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get base list
String[] items = getActivity().getResources().getStringArray(R.array.rs_list);
//Get selected items & set intent args
SparseBooleanArray selectedItems = getListView().getCheckedItemPositions();
ArrayList<String> argList = new ArrayList<>();
for (int i = 0; i < selectedItems.size(); i++) {
argList.add(items[selectedItems.keyAt(i)]);
}
//Start activity
Intent intent = new Intent();
intent.putStringArrayListExtra("SelectedItems", argList);
getActivity().startActivity(intent);
}
});
How can I change the text size of TextView of a fragment. I need it, because text size is small, maybe some users want it to get bigger.
I see, some people advise to use seekbar, or pinch-to-zoom but I can not make it work in a fragment.
Thanks for your help.
my fragment_one.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="org.aultoon.webovietab.fragments.OneFragment"
android:id="#+id/oneFragmentId"
>
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fadingEdge="none"
android:fillViewport="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="top|center"
android:gravity="center"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tvFragmentOne"
android:text="#string/turkce1"
android:textSize="27sp"
android:textIsSelectable="true"
android:layout_margin="10dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
</ScrollView>
here is the my OneFragment.java
public class OneFragment extends Fragment {
//static WebView mWebview;
public OneFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
return rootView;
}
}
here is the my activity
public class SimpleTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "tab1");
adapter.addFragment(new TwoFragment(), "tab2");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.aboutMenuItem:
Intent i = new Intent(this, About_Activity.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
First, please read the following Q&A about the textsize "sp" unit in android. You should understand why it used sp as unit for textView and your question should be solved.
Should use "sp" instead of "dp" for text sizes
What is the difference between "px", "dp", "dip" and "sp" on Android?
Android sp vs dp texts - what would adjust the 'scale' and what is the philosophy of support
http://www.singhajit.com/tutorial-1-android-ui-desgin-and-styling/
Now, you should know the usage of "sp" unit in TextView since it can be adjusted due to the user accessibility setting. That's mean if your boss cannot see it clearly, he/she can set the font size setting in the devices instead of code change.
If you still need workaround for the programming. Here is the solution
I have added the seekbar in your fragment layout.
Update xml.
<RelativeLayout android:id="#+id/oneFragmentId"
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"
>
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"/>
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBar"
android:fadingEdge="none"
android:fillViewport="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:gravity="center"
android:orientation="vertical"
>
<TextView
android:id="#+id/tvFragmentOne"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"
android:text="Hello world"
android:textIsSelectable="true"
android:textSize="27sp"
/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
I have change your textView text as "Hello world" for testing, please change back to your own string resource.
Here is the fragment code.
public class OneFragment extends Fragment {
//static WebView mWebview;
public OneFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
final TextView tvFragmentOne = (TextView) rootView.findViewById(R.id.tvFragmentOne);
SeekBar lSeekBar = (SeekBar) rootView.findViewById(R.id.seekBar);
lSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tvFragmentOne.setTextSize(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
return rootView;
}
}
If you like to use other control pinch to zoom, up/down button or other control component to change the text size of the textview, you can do it with the following procedures:
Change other widget instead of seekbar
Change the listener for listening the component control change( like OnSeekBarChangeListener )
Reset the textView size
I use action bar tabs android studio, his div on section and I want that touch section I cause scrolling activity! I dont want work with a fragments, I want see in my section scrolling activity.
Help please, because long time sit in this trouble.
This is what I want to achieve:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
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 = inflater.inflate(R.layout.fragment_main, container, false);
//TextView textView = (TextView) rootView.findViewById(R.id.section_label);
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
case 3:
return "Секція 4";
}
return null;
}
}
}
main_activity.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.vladislav.scrolable.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"
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.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
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.vladislav.scrolable.MainActivity$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
After tinkering with your code in git, we can make a scrollable TabLayout by changing the fragment_main.xml to:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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.vladislav.scrolable.MainActivity$PlaceholderFragment"
>
<android.support.v4.widget.NestedScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
>
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</android.support.v4.widget.NestedScrollView>
</RelativeLayout>
We must set the layout_width and layout_height of NestedScrollView to match_parent so that we can scroll the layout when we scrolling up the TextView.
Remember that we need to add the following code to NestedScrollView:
app:layout_behavior="#string/appbar_scrolling_view_behavior"
to inform AppBarLayout about the scrolling.
Please look at your Scrolable project after my edit in my Scrolable github.
Sample picture after scrolling up:
I'm trying to get a simple TabLayout with 3 tabs. Having follow different tutorials, my tab don't show up on the final result ( There is just 3 empty tab with no text ).
This how I try to add those tabs:
First the xml layout container the ViewPager (communitylayout)
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:padding="4dip"
android:layout_above="#+id/bottomcontent3"
android:gravity="center_horizontal"
android:background="#android:color/white"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/comtabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
android:background="#android:color/white" />
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/compager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</android.support.design.widget.AppBarLayout>
The Tab xml (tabtext):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tabtext"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#color/tab_text_color"
/>
</RelativeLayout>
And finally the java class where I try to add those Tabs:
super.onSaveInstanceState(savedInstanceState);
view = inflater.inflate(R.layout.communitylayout, container, false); // communitylayout is the first xml I put, see above
Bundle data = getArguments();
MainActivity.addShapeAndBottom(inflater, view, "com", this);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.comtabs);
// add tabs
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
RelativeLayout layout1 = (RelativeLayout) inflater.inflate(R.layout.communitytablayout, container, false);
RelativeLayout layout2 = (RelativeLayout) inflater.inflate(R.layout.communitytablayout, container, false);
RelativeLayout layout3 = (RelativeLayout) inflater.inflate(R.layout.communitytablayout, container, false);
//tab is an array of Strings containing the Tab name
((TextView)layout1.findViewById(R.id.tabtext)).setText(tabs[0]);
((TextView)layout2.findViewById(R.id.tabtext)).setText(tabs[1]);
((TextView)layout3.findViewById(R.id.tabtext)).setText(tabs[2]);
tabLayout.getTabAt(0).setCustomView(layout1);
tabLayout.getTabAt(1).setCustomView(layout2);
tabLayout.getTabAt(2).setCustomView(layout3);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
ViewPager pager = (ViewPager) view.findViewById(R.id.compager);
CommunityPagerFragment adapter = new CommunityPagerFragment(getChildFragmentManager());
pager.setAdapter(adapter);
tabLayout.setupWithViewPager(pager);
//tabLayout.set
return view;
I'm kind of lost, I don't know why my Tabs remain invisible. Thanks in advance.
EDIT Here is my adapter:
public class CommunityPagerFragment extends FragmentPagerAdapter {
public CommunityPagerFragment(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new BlogFragment();
case 1:
return new NewsFragment();
case 2:
return new FAQFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
public class BlogFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.communitylistview, container, false);
return view;
}
}
public class NewsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.communitylistview, container, false);
/*ProgressBar loadingAnim = new ProgressBar(getContext());
loadingAnim.setLayoutParams(new LinearLayout.LayoutParams(40,40));
container.addView(loadingAnim);*/
return view;
}
}
public class FAQFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.communitylistview, container, false);
return view;
}
}
}
You aready have a viewpager, why don't you use setupWithViewPager method?
getTabbar().setupWithViewPager(viewPager);
Add fragment to adapter
BaseFragmentPagerAdapter adapter = new BaseFragmentPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ExampleListedRecyclerViewFragment(), "Tab title 1", false);
adapter.addFragment(new ExampleGridedRecyclerViewFragment(), "Tab title 2", false);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
ViewPager adapter
public class BaseFragmentPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public BaseFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
addFragment(fragment, title, true);
}
public void addFragment(Fragment fragment, String title, boolean hasOptionsMenu) {
fragment.setHasOptionsMenu(hasOptionsMenu);
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
if you want to set an icon to tab item instead of text title:
tabLayout.getTabAt(i).setIcon(iconDrawable);
more detials please see my project
https://github.com/DanielShum/MaterialAppBase/blob/master/materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/base/BaseTabbableActionbarActivity.java
https://github.com/DanielShum/MaterialAppBase/
Try this:
Element tab XML where you want:
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlways"
></android.support.design.widget.TabLayout>
In your MainActivity:
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setTabMode(TabLayout.MODE_FIXED);
tabs.addTab(tabs.newTab().setText("Tab 1"));
tabs.addTab(tabs.newTab().setText("Tab 2"));
tabs.addTab(tabs.newTab().setText("Tab 3"));
The key was to setupWithViewpager first before managing the tabs.
setupWithViewpager first before managing the tabs.
xml layout:
<android.support.v7.widget.Toolbar`enter code here`
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/coloricon" />
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
app:tabMode="fixed" >
<android.support.design.widget.TabItem
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<android.support.design.widget.TabItem
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#android:color/white"/>
in Fragment :
public class myfragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_xml, container, false);
TabLayout tabLayout = V.findViewById(R.id.tablayout);
TabItem tabScan = V.findViewById(R.id.tab1);
TabItem tabCreate = V.findViewById(R.id.tab2);
final ViewPager viewPager = (ViewPager) V.findViewById(R.id.viewpager);
viewPager.setAdapter(new PagerAdapter(getFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//setupWithViewpager first before managing the tabs.
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.getTabAt(0).setText("1");
tabLayout.getTabAt(1).setText("2");
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#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) {
}
});
return V;
}
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new fragment1();
case 1:
return new fragment2();
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
}
I want to be able to click on buttons to navigate forward and backward through several views as well as swiping left or right between views.
So I decided to implement the ViewPager for swiping between multiple views.
Here's my code:
layout xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
<ImageView
android:id="#+id/apple"
android:layout_width="200sp"
android:layout_height="150sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/apple"
android:contentDescription="apple"/>
<TextView
android:id="#+id/number"
android:layout_width="100sp"
android:layout_height="55sp"
android:layout_marginTop="47dp"
android:layout_below="#+id/apple" android:layout_alignStart="#+id/apple"/>
<Button
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/save"
android:layout_alignTop="#+id/ignore" android:layout_toStartOf="#+id/apple"/>
<Button
android:id="#+id/ignore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Ignore"
android:layout_alignParentBottom="true" android:layout_toEndOf="#+id/apple"/>
<ImageView
android:id="#+id/back_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_back"
android:contentDescription="back">
</ImageView>
<ImageView
android:id="#+id/forward_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_forward"
android:layout_alignParentTop="true" android:layout_alignParentEnd="true"
android:contentDescription="forward">
</ImageView>
</RelativeLayout>
Here's my activity:
public class CollectionPager extends Activity {
private PagerAdapter pagerAdapter;
ActionBar actionbar;
MyAdapter myAdapter;
private Context context;
private TextView textView;
private int currentPage;
ViewPager viewPager;
int progressChanged = 0;
public static final String TAG = "CollectionPager";
public CollectionPager() {
context = this;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.collection);
viewPager = (ViewPager) findViewById(R.id.viewPager);
myAdapter = new MyAdapter();
viewPager.setAdapter(myAdapter);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.hide();
}
//Initialize the back button and add an onClick event listener to the button
final ImageView back_button = (ImageView) findViewById(R.id.back_nav_arrow);
back_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the first item
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
});
//Initialize the forward button and add an onClick event listener to the button
final ImageView forward_button = (ImageView) findViewById(R.id.forward_nav_arrow);
forward_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the last item
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
});
final Button save_button = (Button) findViewById(R.id.save);
save_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//save
}
});
final Button ignore_button = (Button) findViewById(R.id.ignore);
ignore_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//ignore
}
});
//Attach the page change listener inside the activity
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
//This method will be invoked when a new page becomes selected
#Override
public void onPageSelected(int position) {
//get position
currentPage = position;
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int i) {
//get state
}
});
}
private class MyAdapter extends PagerAdapter {
int NumberOfPages = 10;
LayoutInflater inflater = (LayoutInflater) CollectionPager.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public int getCount() {
return NumberOfPages;
}
#Override
public Object instantiateItem(ViewGroup parent, int position) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.collection, parent, false);
ImageView imageView = (ImageView) view
.findViewById(R.id.apple);
imageView.setImageResource(R.drawable.apple);
parent.addView(view,0);
return view;
}
#Override
public void destroyItem(ViewGroup parent, int position, Object object) {
((ViewPager) parent).removeView((View) object);
}
#Override
public boolean isViewFromObject(View parent, Object object) {
return parent== ((View) object);
}
#Override
public Parcelable saveState() {
return null;
}
}
}
The onClickEvent is detected but here's a screenshot on what is happening to the view. Two view on top of each other. One view is fixed on the screen and the other one is scrolling correctly.
I'm not sure why this happens. What is causing this to occur in my code?
EDIT: Here's a video highlighting the issue: https://www.dropbox.com/s/6x5qa16xyttzrwa/VIDEO0041.mp4?dl=0
Change
#Override
public boolean isViewFromObject(View parent, Object object) {
return parent== ((View) object);
}
to
#Override
public boolean isViewFromObject(View v, Object o) {
return parent == object;
}
Update:
After watching your movie your problem is you put some static wedget on the top of your viewpager, so remove that, which means your layout will become something like this:
This is your main_activity.xml you must assign it to your activity by function setContentView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
</RelativeLayout>
then at instantiateItem use below layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
>
<ImageView
android:id="#+id/apple"
android:layout_width="200sp"
android:layout_height="150sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/apple"
android:contentDescription="apple"/>
<TextView
android:id="#+id/number"
android:layout_width="100sp"
android:layout_height="55sp"
android:layout_marginTop="47dp"
android:layout_below="#+id/apple" android:layout_alignStart="#+id/apple"/>
<Button
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/save"
android:layout_alignTop="#+id/ignore" android:layout_toStartOf="#+id/apple"/>
<Button
android:id="#+id/ignore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Ignore"
android:layout_alignParentBottom="true" android:layout_toEndOf="#+id/apple"/>
<ImageView
android:id="#+id/back_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_back"
android:contentDescription="back">
</ImageView>
<ImageView
android:id="#+id/forward_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_forward"
android:layout_alignParentTop="true" android:layout_alignParentEnd="true"
android:contentDescription="forward">
</ImageView>
your main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.collection);
viewPager = (ViewPager) findViewById(R.id.viewPager);
myAdapter = new MyAdapter();
viewPager.setAdapter(myAdapter);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.hide();
}
//Attach the page change listener inside the activity
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
//This method will be invoked when a new page becomes selected
#Override
public void onPageSelected(int position) {
//get position
currentPage = position;
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int i) {
//get state
}
});
}
then assign your click listener of your main activity at this function
#Override
public Object instantiateItem(ViewGroup parent, int position) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.collection, parent, false);
ImageView imageView = (ImageView) view
.findViewById(R.id.apple);
imageView.setImageResource(R.drawable.apple);
final ImageView back_button = (ImageView) view.findViewById(R.id.back_nav_arrow);
back_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the first item
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
});
parent.addView(view,0);
return view;
}