Android how to name tabs? - java

I would like to give my tabs names in my main.xml file. After a lot of searching i still havent found a working solution. if someone can provide a working solution/suggestion for this, all be it programatically or with xml i would be very thankful.
main_activity.java
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private TabLayout mTabLayout;
private ViewPager mPager;
private MyPagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyPagerAdapter(getSupportFragmentManager());
mToolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mToolbar);
mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mTabLayout.setTabsFromPagerAdapter(mAdapter);
mTabLayout.setupWithViewPager(mPager);
mPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
}
#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);
}
public static class MyFragment extends Fragment {
public static final java.lang.String ARG_PAGE = "arg_page";
public MyFragment() {
}
public static MyFragment newInstance(int pageNumber) {
MyFragment myFragment = new MyFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE, pageNumber + 1);
myFragment.setArguments(arguments);
return myFragment;
}
}
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = MainActivity.MyFragment.newInstance(position); //FRAGMENT fragment;
switch (position) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
default:
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return "Fragment " + (position + 1);
}
}
main.xml
<LinearLayout 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:orientation="vertical"
tools:context="com.example.lvlastuin.tabnav.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabGravity="fill"
app:tabMaxWidth="0dp"
app:tabTextAppearance="#style/TextAppearance.Design.Tab"
app:tabSelectedTextColor="#color/colorAccent"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>

over ride this method in your pager adapter
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "tab1 name";
case 1:
return "tab2 name";
}
return null;
}

In your MyPagerAdapter class you have a
#Override
public CharSequence getPageTitle(int position) {
return "Fragment " + (position + 1);
}
Which is generally where you set the names of the tabs. So when you instantiate it, just pass a collection of names you'd like to name the tabs

Related

What is the proper way to do a fragment in Android?

I'm relatively new to Android Studio and I'm doing an app, one of it's interface's function is to show the data of various user's and I saw various tutorials on how to list data using FirebaseRecyclerAdapter but they are not working. And now I'm trying to do fragments which I don't know how to do yet.
I'd like to know if this code is properly set up to do a fragment.
My MainActivity.java
public class MainActivity extends AppCompatActivity {
private RelativeLayout pills_layout, appoint_layout, add_pills_layout, add_appoints_layout, account_layout, add_button;
private TextView AccountName0, AccountAge0;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private FirebaseRecyclerAdapter adapter;
private View view;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
Home();
return true;
case R.id.navigation_pills:
Pills();
return true;
case R.id.navigation_appointment:
Appointment();
return true;
case R.id.navigation_account:
Account();
return true;
}
return false;
}
};
public MainActivity() {
}
private void Account(){
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.account);
pills_layout.setVisibility(View.GONE);
appoint_layout.setVisibility(View.GONE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.VISIBLE);
add_button.setVisibility(View.VISIBLE);
/*Button accountChangePass = findViewById(R.id.AccountChangePass);
accountChangePass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent ChangePW = new Intent(MainActivity.this, ChangePW.class);
startActivity(ChangePW);
}
});*/
}
private void Appointment() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.add_appoints);
pills_layout.setVisibility(View.GONE);
appoint_layout.setVisibility(View.GONE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.VISIBLE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.VISIBLE);
}
private void Pills() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.add_pills);
pills_layout.setVisibility(View.GONE);
appoint_layout.setVisibility(View.GONE);
add_pills_layout.setVisibility(View.VISIBLE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.VISIBLE);
}
private void Home() {
pills_layout.setVisibility(View.VISIBLE);
appoint_layout.setVisibility(View.VISIBLE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.GONE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null) {
Intent VerifyLogin = new Intent(MainActivity.this, Launcher.class);
VerifyLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(VerifyLogin);
}
pills_layout = findViewById(R.id.pills_layout);
appoint_layout = findViewById(R.id.appoint_layout);
add_pills_layout = findViewById(R.id.add_pills);
add_appoints_layout = findViewById(R.id.add_appoints);
//account_layout = findViewById(R.id.accountlist);
AccountName0 = findViewById(R.id.AccountName0);
AccountAge0 = findViewById(R.id.AccountAge0);
add_button = findViewById(R.id.add);
pills_layout.setVisibility(View.VISIBLE);
appoint_layout.setVisibility(View.VISIBLE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.GONE);
recyclerView = findViewById(R.id.accountlist);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public RelativeLayout root;
public TextView txtTitle;
public TextView txtDesc;
public ViewHolder(View itemView) {
super(itemView);
root = itemView.findViewById(R.id.account);
txtTitle = itemView.findViewById(R.id.AccountName0);
txtDesc = itemView.findViewById(R.id.AccountAge0);
}
public void setTxtTitle(String string) {
txtTitle.setText(string);
}
public void setTxtDesc(String string) {
txtDesc.setText(string);
}
}
#Override
protected void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Users");
FirebaseRecyclerOptions<Account> options =
new FirebaseRecyclerOptions.Builder<Account>()
.setQuery(query, new SnapshotParser<Account>() {
#NonNull
#Override
public Account parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Account(snapshot.child("name").getValue().toString(),
snapshot.child("idade").getValue().toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Account, ViewHolder>(options) {
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.account, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(ViewHolder holder, final int position, Account model) {
holder.setTxtTitle(model.getName());
holder.setTxtDesc(model.getIdade());
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Users");
FirebaseRecyclerOptions<Account> options =
new FirebaseRecyclerOptions.Builder<Account>()
.setQuery(query, new SnapshotParser<Account>() {
#NonNull
#Override
public Account parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Account(snapshot.child("name").getValue().toString(),
snapshot.child("idade").getValue().toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Account, ViewHolder>(options) {
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.account, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(ViewHolder holder, final int position, Account model) {
holder.setTxtTitle(model.getName());
holder.setTxtDesc(model.getIdade());
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
adapter.stopListening();
}
};
My Account.java
public class Account {
private String name, idade;
public Account() {
}
public Account(String name, String idade) {
this.name = name;
this.idade = idade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdade() {
return idade;
}
public void setIdade(String idade) {
this.idade = idade;
}
}
My account.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/account">
<RelativeLayout
android:id="#+id/AccountUser"
android:layout_width="match_parent"
android:layout_height="163dp"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="15dp"
android:background="#drawable/edit_bg"
android:padding="15dp">
<RelativeLayout
android:id="#+id/AccountImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/AccountInfos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/AccountImage"
android:layout_toEndOf="#id/AccountImage"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp">
<TextView
android:id="#+id/AccountName0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="Nome1"
android:textColor="#color/colorWhite"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/AccountAge0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountName0"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="Idade1"
android:textColor="#color/colorWhite"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="#+id/AccountChangePass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountAge0"
android:text="Mudar Palavra-Passe"
android:textColor="#color/colorWhite"
android:textSize="18sp"
android:textStyle="bold"
android:textAllCaps="false"
android:padding="10dp"
android:layout_marginTop="10dp"
android:background="#drawable/custom_button"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
the best way to do that in my opinion is using Fragments.
Create 3 fragments:
Just check the checkBox that says " Create layout XML? "
Create a java class and add this code after create 3 fragments:
public class /* class name 1 */ extends FragmentPagerAdapter {
public /* class name 1 */ (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment1 fragment1= new Fragment1 ();
return fragment1;
case 1:
Fragment2 fragment2 = new Fragment2();
return fragment2 ;
case 2:
Fragment3 fragment3 = new Fragment3 ();
return fragment3 ;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position){
switch (position){
case 0:
return "/* set a name to fragment1*/";
case 1:
return "/* set a name to fragment2*/";
case 2:
return "/* set a name to fragment3*/";
default:
return null;
}
}
}
Now in your mainActivity.java add this code:
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private /* class name 1 */ mSectionsPagerAdapter;
private TabLayout mTabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = findViewById(R.id.main_tabPager);
mSectionsPagerAdapter = new /* class name 1 */(getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
mTabLayout = findViewById(R.id.main_tabs);
mTabLayout.setupWithViewPager(mViewPager);
}
}
Now in your mainactivity.xml add this:
<android.support.v4.view.ViewPager
android:id="#+id/main_tabPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:visibility="visible"
tools:ignore="UnknownId"></android.support.v4.view.ViewPager>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:id="#+id/main_tabs">
</android.support.design.widget.TabLayout>
The final result will look like this:
I suppose pills_layout, appoint_layout, .. are your fragment layouts.
Maintaining them by changing their VISIBILITY property is not a good idea.
You have to use the supportFragmentManager instead.
Create a loadFragment method like this
public final boolean loadFragment(#NotNull Fragment fragment) {
this.getSupportFragmentManager().beginTransaction()
.replace(<<id of your fragment container layout>>, fragment, "fragment").commit();
return true;
}
And change your onNavigationItemSelected method to this:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return loadFragment(new HomeFragment());
case R.id.navigation_pills:
return loadFragment(new PillsFragment());
case R.id.navigation_appointment:
return loadFragment(new AppointmentFragment());
case R.id.navigation_account:
return loadFragment(new AccountFragment());
}
return false;
}
};
Now make a seperate class for each fragment and inflate the layout of the right fragment.
here is an example of how your HomeFragment-class has to look like this:
public final class HomeFragment extends Fragment {
#Override
public View onCreate(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.<<your homefragment layout name>>, null);
}
}
I hope it's enough to help you out. I'm sorry if there are little mistakes in syntax, I'm used to code Android in Kotlin. But you will get the idea behind it.

RecyclerView: No adapter attached; skipping layout - What is missing in the main?

Before put -1 in the score, I tell you that I read all, I repeat ALL the answers about this problem in this site and even in other site, so, if you can give me an hand.
Hi guys, i'm having this problem with my application and I'm wasting too much time in this.
My application is composed by 4 fragments, and I'm having problems with the two with the recyclerview (in fragment_fibra and fragment_adsl).
main.java
public class main extends AppCompatActivity implements
OnFragmentInteractionListener //I HAVE a problem with
OnFragmentInteractionListener {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
// tabLayout.setupWithViewPager(mViewPager); //aggiunta dopo
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#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_homepage, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
break;
case 3:
rootView = inflater.inflate(R.layout.fragment_adsl, container, false);
break;
case 4:
rootView = inflater.inflate(R.layout.fragment_aiuto, container, false);
break;
}
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return PlaceholderFragment.newInstance(1);
case 1:
return PlaceholderFragment.newInstance(2);
case 2:
return PlaceholderFragment.newInstance(3);
case 3:
return PlaceholderFragment.newInstance(4);
default: return PlaceholderFragment.newInstance(1);
// here i have other problems, so like this the app still work, but if i change something it crash (and I know it's wrong like this)
}
//return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 4;
}
}
}
activity_homepage.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=".homepage">
<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.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="#color/colorPrimaryDark"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/PopupOverlay"
app:title="#string/app_name">
</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:background="#color/colorPrimary">
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_3" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_4" />
</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>
homepage.java (first fragment)
public class homepage extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_homepage, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
break;
case 3:
rootView = inflater.inflate(R.layout.fragment_adsl, container, false);
break;
case 4:
rootView = inflater.inflate(R.layout.fragment_aiuto, container, false);
break;
}
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 4;
}
}
}
fragment_fibra.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".fibra"
android:background="#EFEFEF">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:drawablePadding="22dp"
android:gravity="center"
android:hint="#string/cercasugg"
android:textColor="#000000"
android:padding="16dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/ListaFibra"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
fibra.java (second fragment)
public class fibra extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private OnFragmentInteractionListener mListener;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
public fibra() {
}
public static fibra newInstance(String param1, String param2) {
fibra fragment = new fibra();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_fibra, container, false);
recyclerView = V.findViewById(R.id.ListaFibra);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
List<String> input = new ArrayList<>();
for (int i = 0; i < 100; i++) {
input.add("Test" + i);
}
mAdapter = new adFibra(input);
recyclerView.setAdapter(mAdapter);
return V;
/*View rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.ListaFibra);
recyclerView.setHasFixedSize(true); //per migliorare performance
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
adFibra adapter = new adFibra(new String[]{"Example One"});
recyclerView.setAdapter(adapter);
return rootView;*/
//return inflater.inflate(R.layout.fragment_fibra, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
try to put
recyclerView.setLayoutManager(llm);
before
recyclerView.setAdapter(adapter);
so it will be
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
MyAdapter adapter = new MyAdapter(new String[]{"Example One", "Example Two", "Example Three", "Example Four", "Example Five" , "Example Six" , "Example Seven"});
recyclerView.setAdapter(adapter);
Happy Coding :D
Are you sure you actually call the fibra fragment?
You are creating a PlaceHolderFragment every time and just inflating different layouts. You don't actually create a fibra fragment, so the recycler is not populated, thus the message.
In your SectionsPagerAdapter, in method getItem, return the fragment instance that corresponds to the position.
For example:
switch (position) {
case 0:
return homepage.newInstance();
case 1:
return fibra.newInstance();
case 2:
return adsl.newInstance();
case 3:
return aiuto.newInstance();
default:
return homepage.newInstance();
}
Remove the PlaceHolderFragment from your main activity. Also homepage is not a fragment, but an activity. All your fragments should look like fibra.
And implement all the fragment interfaces like:
implements fibra.OnFragmentInteractionListener
and create a method to implement it:
#Override
public void onFragmentInteraction(Uri uri) {
// your code here...
}

How to create a Tabbed Activity with ListViews - Android

First of all, I'm a beginner in Android programming. What I'm trying to do is to program three Tabs with each a ListView inside (you know it from e.g. WhatsApp). Android Studio makes it easy to automatically create a Tabbed Activity. So the question is: how can I implement a ListView for each Tab?
Actually there is a nice tutorial on http://www.androidhive.info/2012/05/android-combining-tab-layout-and-list-view/ which uses TabActivity. However this method is deprecated and Fragments should be used instead. I have extended main_fragment.xml (which was created by Android Studio) with a ListView. But what is the correct way to set the corresponding list adapters and especially where to set them? Setting them like ListView list_all = (ListView) findViewById(R.id.listViewAll) in onCreate() does not work because of a null object reference error. Also I didn't find out how to use the rootView which is returned by onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) So how can I solve this problem?
main_fragment.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:background="#color/colorAccent"
android:paddingTop="#dimen/activity_vertical_margin">
<ListView
android:id="#+id/listViewAll"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</RelativeLayout>
main.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"
android:background="#color/white"
tools:context="de.url.members">
<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:background="#color/bg_login_dark"
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="#color/bg_login_dark"
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"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
app:tabMode="fixed"
android:fillViewport="false" />
</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>
main.java:
public class main 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.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) {
// action here
}
});
}
#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_members, 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.logout) {
//action here
}
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) {
int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);//INDEX of selected TAB
View rootView;
if (sectionNumber == 1){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 2){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 3){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else{
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}
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 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getResources().getString(R.string.title_section1);
case 1:
return getResources().getString(R.string.title_section2);
case 2:
return getResources().getString(R.string.title_section3);
}
return null;
}
}
}
If you want to use Listing with tablayout and viewpager try this way it will work for you
public class MainActivity extends AppCompatActivity {
private static Toolbar toolbar;
private static ViewPager viewPager;
private static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);//setting tab over viewpager
//Implementing tab selected listener over tablayout
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
Log.e("TAG","TAB1");
break;
case 1:
Log.e("TAG","TAB2");
break;
case 2:
Log.e("TAG","TAB3");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
//Setting View Pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment("ANDROID"), "ANDROID");
adapter.addFrag(new DummyFragment("iOS"), "iOS");
adapter.addFrag(new DummyFragment("WINDOWS"), "WINDOWS");
viewPager.setAdapter(adapter);
}
//View Pager fragments setting adapter class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();//fragment arraylist
private final List<String> mFragmentTitleList = new ArrayList<>();//title arraylist
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
//adding fragments and title method
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
For more see android-material-design-tabs-using-tablayout
OR
Check this http://www.tutorialsbuzz.com/2015/10/Android-Sliding-TabLayout-ListView-WhatsApp.html
And check this https://github.com/codepath/android_guides/wiki/Handling-Scrolls-with-CoordinatorLayout
OUTPUT
I will explain what you have to do to put a ListView on one of the fragments. (Sorry if I write a bad English)
You should put your listView view on the xml witch is displayed by one of your fragments. In the code that you have post the layout witch fragment displays is R.layout.main_fragment
Then on the fragment you have to declare your ListView:
ListView list_all = (ListView) rootView.findViewById(R.id.listViewAll);
You have to create a ListView adapter, an object class and some other files, you can use the tutorial witch you have post.
Link
Then write your code to set an Adapter to this ListView after the rootView is assigned on the fragment:
if (sectionNumber == 1){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 2){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 3){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else{
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}
ArrayList<Object> arrayListOfObjects = new ArrayList<>();
arrayListOfObjects.add(new Object(...));
MyAdapter adapter = new MyAdapter(arrayListOfObjects);
list_all.setListAdapter(adapter);
I have solved it now by simply editing the getItem() method of public class SectionsPagerAdapter in main.java.
Just return a default ListFragment instead of the PlaceholderFragment.
Interesting note: Returning the same ListFragment object for all tabs leads to an error.
main.java:
public class MainActivity extends AppCompatActivity {
private ArrayAdapter<String> adapter;
private ListFragment contacts1 = new ListFragment();
private ListFragment contacts2 = new ListFragment();
private ListFragment contacts3 = new ListFragment();
List<String> words = new ArrayList<String>();
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);
words.add("Hello");
words.add("World");
words.add("!");
adapter = new ArrayAdapter<String>(this,R.layout.item,words);
contacts1.setListAdapter(adapter);
contacts2.setListAdapter(adapter);
contacts3.setListAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Update List", Snackbar.LENGTH_LONG).setAction("Action", null).show();
words.add("New Item");
adapter.notifyDataSetInvalidated();
}
});
}
#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);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public ListFragment getItem(int position) {
if (position == 0){
return contacts1;
}else if (position == 1){
return contacts2;
}else{
return contacts3;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}

Android ViewPager child fragments load but tabs don't

I'm using a ViewPager in a fragment that loads a child fragment per tab, and that is working fine the child fragments are loaded, but the issue is that the tabs themselves, where the tab click-able names go, is not showing, nor is it responding to click events. I reach this screen by selecting an element in a recyclerview in a previous fragment.
The expected layout structure is the following:
But the problem is that, although everything else loads fine and I can side swipe to switch child fragments, the tab bar doesn't load at all and I just get this:
I'm not sure what is causing this, but when I rotate the screen and back, then they appear.
MainActivity class
public class MainActivity extends AppCompatActivity {
private final static int PROFILE_FRAGMENT = 1;
private final static int PRIZES_FRAGMENT = 2;
private final static int STORES_FRAGMENT = 3;
private final static int ABOUT = 4;
private int currentFragment = 3;
private String currentFragmentName = "StoresListFragment";
public int HEADER_IMAGE = R.drawable.avatar;
private DrawerLayout drawer;
private List<DrawerItem> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
FragmentManager fm = getSupportFragmentManager();
if (getIntent().getStringExtra("STORE_DETAILS") != null) {
openFragment(new StoreDetailsFragment());
setTitle(getString(R.string.title_store_details));
}
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
mRecyclerView.setHasFixedSize(true);
dataList = new ArrayList<>();
addItemsToDataList();
NavDrawerAdapter mAdapter = new NavDrawerAdapter(dataList, this, db.getClientName(), db.getPoints(), HEADER_IMAGE);
mRecyclerView.setAdapter(mAdapter);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
drawer.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
drawer.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
onTouchDrawer(currentFragment);
final GestureDetector mGestureDetector =
new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
drawer.closeDrawers();
onTouchDrawer(recyclerView.getChildLayoutPosition(child));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
private void addItemsToDataList() {
dataList.add(new DrawerItem(getString(R.string.title_profile), R.mipmap.ic_action_profile));
dataList.add(new DrawerItem(getString(R.string.title_prizes), R.mipmap.ic_action_prizes));
dataList.add(new DrawerItem(getString(R.string.title_stores), R.mipmap.ic_action_sales));
dataList.add(new DrawerItem(getString(R.string.title_about), R.mipmap.ic_action_about));
}
public void openFragment(final Fragment fragment) {
if (!fragment.toString().equalsIgnoreCase(currentFragmentName)) {
// update the transfer content by replacing fragments
currentFragmentName = fragment.toString();
switchContent(fragment);
}
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commitAllowingStateLoss();
}
private void onTouchDrawer(final int position) {
currentFragment = position;
switch (position) {
case PROFILE_FRAGMENT:
openFragment(new ProfileFragment());
setTitle(getString(R.string.title_profile));
break;
case PRIZES_FRAGMENT:
openFragment(new PrizesListFragment());
setTitle(getString(R.string.title_prizes));
break;
case STORES_FRAGMENT:
openFragment(new StoresListFragment());
setTitle(getString(R.string.title_stores));
break;
case ABOUT:
openFragment(new AboutFragment());
setTitle(getString(R.string.title_about));
break;
default:
}
}
/*
* helper to switch content with backstack
*/
public void switchContent(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
// add to backstack
.addToBackStack(fragment.getClass().getSimpleName())
.commitAllowingStateLoss();
}
#Override
protected void onResume() {
if (getIntent().getStringExtra("SALES_LIST") != null) {
openFragment(new StoreDetailsFragment());
setTitle(getString(R.string.title_store_details));
} else if (getSupportFragmentManager().getBackStackEntryCount() <= 0) {
openFragment(new StoresListFragment());
setTitle(getString(R.string.title_stores));
}
super.onResume();
}
}
The fragment in question:
public class StoreDetailsFragment extends Fragment {
private ViewPager viewPager;
private Store storeSelected = null;
private TextView storeName;
private ImageView bannerImage;
private TextView storesubtitle;
public StoreDetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_store_details, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.tabanim_viewpager);
TabLayout storeTabLayout = (TabLayout) rootView.findViewById(R.id.tabanim_tabs);
setupViewPager(viewPager);
storeTabLayout.setupWithViewPager(viewPager);
storeTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
Toast.makeText(getActivity(), "Sales List", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getActivity(), "Store Description", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getActivity(), "Store Ratings", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(getActivity(), "Images", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
bannerImage = (ImageView) rootView.findViewById(R.id.store_details_banner_image);
storeName = (TextView) rootView.findViewById(R.id.text_store_details_name);
storesubtitle = (TextView) rootView.findViewById(R.id.text_store_details_subtitle);
return rootView;
}
#Override
public void onResume() {
super.onResume();
// Set title
getMainActivity().setTitle(R.string.title_store_details);
}
protected MainActivity getMainActivity() {
return (MainActivity) getActivity();
}
}
Fragment in question's layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:id="#+id/main_content"
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:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="300dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/store_details_banner_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"
android:background="#drawable/white_placeholder"
android:contentDescription=""
android:fitsSystemWindows="true"/>
<LinearLayout
android:id="#+id/smth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="?attr/actionBarSize"
android:background="#ffffff"
android:orientation="vertical">
<TextView
android:id="#+id/text_store_details_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="18dp"
android:layout_marginTop="40dp"
android:textColor="#333"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/text_store_details_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginStart="13dp"
android:layout_marginTop="3dp"
android:drawableLeft="#mipmap/ic_action_store_house"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#333"/>
</LinearLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/anim_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/transparent"
app:layout_collapseMode="parallax"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabanim_tabs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
android:visibility="visible"
app:tabGravity="center"
app:tabIndicatorColor="#F1514A"
app:tabMode="scrollable"
app:tabSelectedTextColor="#android:color/white"
app:tabTextColor="#99ffffff"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/tabanim_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
And the ViewPagerAdaper:
public class StoreDetailsViewPagerTabAdaper extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public StoreDetailsViewPagerTabAdaper(FragmentManager manager) {
super(manager);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(android.support.v4.app.Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}}
Any help and suggestions are appreciated.
In the end I couldn't find a solution to this and even after consulting some more experienced developers we could only find a workaround, which was just have this be inside an activity instead of a fragment and then the viewpager behaves as expected. I couldn't figure out why it doesn't inside a fragment.
If anyone finds a more suitable answer, go ahead, but until then I'll set this to be the accepted answer.
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
Try this one and initiate your adapter with getChildFragmentManager
I would try to log inside getPageTitle, because I think when you rotate the screen everything is destroyed an the mFragmentTitleList is empty when you redraw the titles, so try to find out what's going on by doing something like:
#Override
public CharSequence getPageTitle(int position) {
Log.d("ViewPagerAdapter", "Displaying title: "+ mFragmentTitleList.get(position));
return mFragmentTitleList.get(position);
}
Your TabLayout might not be showing because you set height to it. Try setting android:layout_height="wrap_content".
You don't have to handle tab clicks manually – if you bind the TabLayout with ViewPager
tabLayout.setupWithViewPager(viewPager);
the listener is created automatically. I would suggest to remove the custom listener.

How can I use a PreferenceFragment with a ViewPager?

I cannot figure out how to get PreferenceFragment to work correctly. I have a ViewPager hooked up to a FragmentPagerAdapter, with two Fragments that the user can swipe between. I am trying to get the "Settings" menu working, using a PreferenceFragment, but I am unsure what I'm doing wrong. When I tap Settings the view is changed to a blank white screen.
My SettingsFragment class:
public class SettingsFragment extends PreferenceFragment{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
My PagerAdapter class:
public class PagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Object instantiateItem(ViewGroup container, int position){
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
#Override
public Fragment getItem(int i) {
switch (i) {
// default case is also case 0 to avoid redundant code
default: return new CalculatorFragment();
case 1: return new TapeFragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 1: return "Review";
default: return "Calculator";
}
}
public Fragment getRegisteredFragment(int position){
return registeredFragments.get(position);
}
}
My main class which should create the PreferenceFragment when user taps "Settings"
public class MangoCalc extends FragmentActivity implements CalculatorFragment.CalcTapeInterface{
PagerAdapter pagerAdapter;
ViewPager myViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
final ActionBar actionBar = getActionBar();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mango_calc);
pagerAdapter = new PagerAdapter(getFragmentManager());
myViewPager = (ViewPager) findViewById(R.id.main);
myViewPager.setAdapter(pagerAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
myViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}
};
for (int i=0; i< pagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(pagerAdapter.getPageTitle(i))
.setTabListener(tabListener));
}
myViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mango_calc, 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();
if (id == R.id.action_settings) {
FragmentManager fm = getFragmentManager();
SettingsFragment settingsFragment = new SettingsFragment();
fm.beginTransaction().replace(R.id.main, settingsFragment).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTapePass(ArrayList<String> data) {
if (data!=null) Log.d("Tape", "Last element got: "+data.get(data.size()-1));
TapeFragment tapeFragment = (TapeFragment) pagerAdapter.getRegisteredFragment(1);
tapeFragment.updateTape(data);
}
}
My preferences.XML
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="#string/lookandfeel">
<ListPreference
android:key="theme_preference"
android:title="#string/theme"
android:summary="#string/summary_theme_preference"
android:entries="#array/entries_theme_preference"
android:entryValues="#array/entryvalues_theme_preference"
android:defaultValue="mango"/>
<SwitchPreference
android:key="keypress_vibration_preference"
android:title="#string/keypress_vibration"
android:summaryOn="#string/summaryon_keypress_vibration_preference"
android:summaryOff="#string/summaryoff_keypress_vibration_preference"
android:switchTextOn="#string/text_keypress_vibration_on"
android:switchTextOff="#string/text_keypress_vibration_off"
android:defaultValue="true" />
</PreferenceCategory>
</PreferenceScreen>
and the XML for the activity:
<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/main"
/>
In your getitem case 1 needs to be listed before the default

Categories