ViewPager doesn't call onCreate and onCreateView fragment methods - java

I created an activity with tabs. However, fragments onCreate and onCreateView are not being invoked.
Here is my Fragment class:
public static class PlaceholderFragment extends Fragment {
private int mPage;
private static final String ARG_PAGE = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
Log.d(TAG, "newInstance: run");
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: run");
if (getArguments() != null) {
mPage = getArguments().getInt(ARG_PAGE);
}
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView: run");
View rootView = inflater.inflate(R.layout.fragment_easy, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.recyclerView2);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
MyAdapter adapter = new MyAdapter(getContext(), initData(mPage));
adapter.setParentClickableViewAnimationDefaultDuration();
adapter.setParentAndIconExpandOnClick(true);
recyclerView.setAdapter(adapter);
return rootView;
}
}
OnCreate method of activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy);
mSectionsPagerAdapter = new SectionsPagerAdapter(new FragmentActivity().getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = findViewById(R.id.viewpager);
mTabLayout = findViewById(R.id.tabs2);
mViewPager.setAdapter(mSectionsPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
}
Fragment XML:
<androidx.constraintlayout.widget.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.stunner.moderstars.ActivityEasy$PlaceholderFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
Activity XML:
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/easy_root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbar2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:layout_scrollFlags="scroll|enterAlways|snap"
ads:menu="#menu/menu_activity_pro"
ads:title="#string/app_name">
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:tabMode="scrollable" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="32dp"
android:src="#drawable/ic_sharp_add"
ads:backgroundTint="#color/AccentColor" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Adapter Class:
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() {
return UsefulThings.checkmods(getApplicationContext()).length+1;
}
#Override
public CharSequence getPageTitle(int position) {
return "Mod #"+ (position+1);
}
}
I've read somewhere, that it can be layout problem, but I don't know what to change there.

Solved. The problem was here:
mSectionsPagerAdapter = new SectionsPagerAdapter(new FragmentActivity().getSupportFragmentManager());
I've corrected this to:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

Related

Textview in a fragment of Viewpager doesn't update right

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) {
}
};
}

RecyclerView No adapter attached

There is an activity with container for fragments, which with a start of activity added ViewPagerFragment. There is a RecyclerView inside of MainFragment (which is tab) which is displayed but not filled with a data.
Tried to change width and high from 0 to Match_Parent and Fixed_Size. Also changed ConstraintLayout to RelativeLayout.Using theme android:theme="#style/MyMaterialTheme"
style.xml
<style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="MyMaterialTheme" parent="MyMaterialTheme.Base">
</style>
E/RecyclerView: No adapter attached; skipping
MainActivity.class
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private AdView mAdView;
private FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdView.loadAd(adRequest);
mFragmentTransaction = getSupportFragmentManager()
.beginTransaction()
.add(R.id.container_frame, new ViewPagerFragment());
mFragmentTransaction.commit();
}
#Override
protected void onResume() {
super.onResume();
mAdView.resume();
}
#Override
protected void onPause() {
super.onPause();
mAdView.pause();
}
#Override
protected void onDestroy() {
mAdView.destroy();
super.onDestroy();
}
activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
tools:context="com.newakkoff.justad.Activities.MainActivity">
<RelativeLayout
ads:layout_constraintBottom_toTopOf="#+id/adView"
ads:layout_constraintTop_toTopOf="parent"
ads:layout_constraintLeft_toLeftOf="parent"
ads:layout_constraintRight_toRightOf="parent"
android:id="#+id/container_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="0dp"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_ad_unit_id"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
tools:layout_constraintRight_creator="1"
tools:layout_constraintLeft_creator="1"
android:layout_height="50dp">
</com.google.android.gms.ads.AdView>
</android.support.constraint.ConstraintLayout>
ViewPagerFragment.class
public class ViewPagerFragment extends Fragment {
private ViewPager mViewPager;
private Toolbar mToolbar;
private TabLayout mTableLayout;
int i = 1;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_view_pager, container, false) ;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager_main);
mViewPager.setAdapter(new CustomPagerAdapter(getActivity()));
mViewPager.setCurrentItem(1);
mTableLayout = (TabLayout) view.findViewById(R.id.tabs);
mTableLayout.setupWithViewPager(mViewPager);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
}
}
fragment_view_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="#+id/appBarLayout"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
<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/view_pager_main"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_width="0dp"
android:layout_height="0dp">
MainFragment.class
public class MainFragment extends Fragment {
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
private LinearLayoutManager mLayoutManager;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLayoutManager = new LinearLayoutManager(this.getActivity(),LinearLayoutManager.VERTICAL,false);
mAdapter = new MyAdapter(new String[]{"test one", "test two", "test three", "test four", "test five", "test six", "test seven"});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
tools:listitem="#layout/card_item"
android:background="#color/colorPrimary"/>
</android.support.constraint.ConstraintLayout>
CustomPageAdapter.class
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ModelPager modelsPager = ModelPager.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelsPager.getLayoutResId(), container, false);
container.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return ModelPager.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelPager customPagerEnum = ModelPager.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
ModelPager.class
public enum ModelPager {
SEND_FRAGMENT(R.string.send_fragment_tab,R.layout.fragment_send),
MAIN_FRAGMENT(R.string.main_fragment_tab, R.layout.fragment_main),
ABOUT_FRAGMENT(R.string.about_fragment_tab, R.layout.fragment_about);
private int mTitleResId;
private int mLayoutResId;
ModelPager(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
MyAdapter.class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
static class MyViewHolder extends RecyclerView.ViewHolder {
private static final String TAG = "My Recycler Adapter";
CardView mCardView;
TextView mTextView;
MyViewHolder(View v) {
super(v);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Element " + getAdapterPosition() + " clicked.");
}
});
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter( String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_item, parent, false);
// set the view's size, margins, paddings and layout parameters
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() {
return mDataset.length;
}
}
card_item.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="68dp" >
<android.support.v7.widget.CardView
android:id="#+id/card_view"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="62dp"
card_view:cardCornerRadius="4dp"
card_view:elevation="14dp">
<TextView
android:id="#+id/tv_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:gravity="center" >
</TextView>
</android.support.v7.widget.CardView>
</RelativeLayout>
The only place that can logically have anything to do with that error is mRecyclerView.setAdapter(mAdapter); since its the only RecyclerView.
Looking at the documentation mAdapter is allowed to be null to represent no adapter. So either that variable is null or it is does not properly implement the RecyclerView.Adapter interface.

Insert Value of Checkbox (ListView) into Database

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);
}
});

Tabs don't appear with TabLayout

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;
}
}
}

Issue Using ViewPager Indicator with Jake Wharton Library

I have downloaded the library and properly included into my android studio project
I am not able to see Circle indicator even after using library:
Here is my code:
MAIN FILE:
public class MyActivity extends FragmentActivity implements OnPageChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
List<Fragment> list = new ArrayList<Fragment>();
list.add(new MyFragment());
list.add(new MyFragment());
list.add(new MyFragment());
MyPagerAdapter a = new MyPagerAdapter(getSupportFragmentManager(), list);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(a);
CirclePageIndicator mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(pager);
}
MyPagerAdapter.java
public class MyPagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm,List<Fragment> f) {
super(fm);
this.fragments = f;
}
#Override
public Fragment getItem(int arg0) {
return fragments.get(arg0);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return fragments.size();
}
}
MyFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanse) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
activity_my.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.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:padding="10dip"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
</android.support.v4.view.ViewPager>
</RelativeLayout>
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/gallery"
android:src="#drawable/pic1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Output:

Categories