Tab Not Changing on click of tab layout items - java

Fragments(tabs) are not changing on click of tab layout(tabs button)
I have tried the following code
MainActivity.java
package com.kunal.flightstatus;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout = findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Favourite"));
tabLayout.addTab(tabLayout.newTab().setText("Search"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = findViewById(R.id.viewpager);
PageAdapter adapter = new PageAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
}
PagerAdapter.java
package com.kunal.flightstatus;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class PageAdapter extends FragmentPagerAdapter {
public PageAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0 :
Tab1 tab1 = new Tab1();
position +=1;
Bundle bundle = new Bundle();
bundle.putString("message","fragment :"+position);
tab1.setArguments(bundle);
return tab1;
case 1 :
Tab2 tab2 = new Tab2();
position +=1;
Bundle bundl = new Bundle();
bundl.putString("message","fragment :"+position);
tab2.setArguments(bundl);
return tab2;
case 2 :
Tab3 tab3 = new Tab3();
position +=1;
Bundle bundlee = new Bundle();
bundlee.putString("message","fragment :"+position);
tab3.setArguments(bundlee);
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="horizontal">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tablayout"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/viewpager">
</androidx.viewpager.widget.ViewPager>
</LinearLayout>
Tabs(fragments) Should change on click of tab layout item

ViewPager and TabLayout need to be linked for tab switching to work.
tabLayout.setupWithViewPager(viewPager);
should do the trick.
That way TabLayout will be connected to the ViewPager and will get filled automatically. Implement CharSequence getPageTitle (int position) in your FragmentPagerAdapter to fill in the titles instead of calling tabLayout.addTab() manually:
#NonNull
private List<String> titles = Arrays.asList("Home", "Favourite", "Search");
#Override
public CharSequence getPageTitle (int position) {
return titles.get(position);
}
The whole setup will look like that:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tablayout"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabGravity="fill" />
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/viewpager" />
</LinearLayout>
activity:
package com.kunal.flightstatus;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewPager viewPager = findViewById(R.id.viewpager);
PageAdapter adapter = new PageAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = findViewById(R.id.tablayout);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
}
}
PagerAdapter:
package com.kunal.flightstatus;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.Arrays;
import java.util.List;
public class PageAdapter extends FragmentPagerAdapter {
#NonNull
private List<String> titles = Arrays.asList("Home", "Favourite", "Search");
public PageAdapter(#NonNull FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
#Override
public CharSequence getPageTitle (int position) {
return titles.get(position);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0 :
Tab1 tab1 = new Tab1();
position +=1;
Bundle bundle = new Bundle();
bundle.putString("message","fragment :"+position);
tab1.setArguments(bundle);
return tab1;
case 1 :
Tab2 tab2 = new Tab2();
position +=1;
Bundle bundl = new Bundle();
bundl.putString("message","fragment :"+position);
tab2.setArguments(bundl);
return tab2;
case 2 :
Tab3 tab3 = new Tab3();
position +=1;
Bundle bundlee = new Bundle();
bundlee.putString("message","fragment :"+position);
tab3.setArguments(bundlee);
return tab3;
default:
throw new IllegalStateException();
}
}
#Override
public int getCount() {
return 3;
}
}

Related

how to make android app in java using navigation drawer and viewpager/viewpager2

hello I am making an application to debate in android studio using Java, I intend that the application occupies a navigation drawer and a viewpager / viewpager2. I am very new programming in androidstudio and therefore I have followed several video tutorials to incorporate viewpager / viepager 2 with navigation drawer but so far none works for me (the navigation drawer only works for me), the last thing I tried was to use viewpager (since with viepager 2 I had problems calling the adapter from the main), but when compiling the project the emulator was I was left with a black screen and it did not show anything. I hope you can help me because this project is very important to me. Here is part of my code:
main:
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import Fragments.generaDebate;
import Fragments.perfil_user;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;
NavigationView navigationView;
//variables para cargar el fragment
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
String personName;
//variable viewpager
ViewPager pager;
TabLayout tablayout;
TabItem first_item,second_item;
pageAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);//se pasa el toolbar
drawerLayout=findViewById(R.id.drawer);
navigationView=findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
actionBarDrawerToggle=new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open,R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
actionBarDrawerToggle.syncState();
//carga viewpager
pager=findViewById(R.id.view);
tablayout=findViewById(R.id.title_menu);
first_item=findViewById(R.id.first_item);
second_item=findViewById(R.id.second_item);
//declarando adapter en el main
FragmentManager fragmentManager;
fragmentManager=getSupportFragmentManager();
adapter=new pageAdapter(fragmentManager, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,tablayout.getTabCount());
pager.setAdapter(adapter);
tablayout.addOnTabSelectedListener(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) {
}
});
pager.addOnAdapterChangeListener((ViewPager.OnAdapterChangeListener) new TabLayout.TabLayoutOnPageChangeListener(tablayout));
//cargar fragment principal
FragmentTransaction fragmentTransaction;
fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, new perfil_user());
fragmentTransaction.commit();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.user){
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
fragmentManager=getSupportFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, new perfil_user());
fragmentTransaction.commit();
}
else if (item.getItemId() == R.id.exit){
//finish();
loggin login=new loggin();
login.signOut();
}
//aquí van las otros fragment
drawerLayout.closeDrawer(GravityCompat.START);
return false;
}
}
adapter:
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.ArrayList;
import Fragments.generaDebate;
import Fragments.perfil_user;
public class pageAdapter extends FragmentPagerAdapter {
private int tabsNumber;
public pageAdapter(#NonNull FragmentManager fm, int behavior,int tabs) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 1:
return new perfil_user ();
case 2:
return new generaDebate();
default:
return null;
}
}
#Override
public int getCount() {
return tabsNumber;
}
}
The navigation drawer is the most common feature offered by android and the navigation drawer is a UI panel that shows your app’s main navigation menu. It is also one of the important UI elements, which provides actions preferable to the users like example changing user profile, changing settings of the application, etc. In this article, it has been discussed step by step to implement the navigation drawer in android
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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:layout_width="match_parent"
android:background="#color/bgColor"
android:layout_height="match_parent"
tools:context=".activities.MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:gravity="center_vertical"
android:background="#color/bgColor"
android:paddingStart="20dp"
android:paddingEnd="20dp"
android:orientation="horizontal">
</LinearLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/vp_horizontal_ntb"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
android:foreground="?attr/selectableItemBackground"
app:menu="#menu/bottom_navigation"
app:elevation="10dp"
app:labelVisibilityMode="labeled"
app:itemIconTint="#color/bottom_navigation_color"
app:itemTextColor="#color/bottom_navigation_color"
app:itemBackground="#color/bottomNavigationBackground"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigationMenu"
android:icon="#android:drawable/ic_menu_sort_by_size"
android:title="Menu" />
<item
android:id="#+id/navigationMyCourses"
android:icon="#drawable/ic_email"
android:title="Courses" />
<item
android:id="#+id/navigationHome"
android:icon="#drawable/ic_home"
android:title="Home" />
<item
android:id="#+id/m_refer"
android:icon="#android:drawable/ic_menu_share"
android:title="Refer" />
<item
android:id="#+id/navigationMyProfile"
android:icon="#drawable/ic_back"
android:title="User" />
</menu>
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(#NonNull #NotNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull
#NotNull
#Override
public Fragment createFragment(int p) {
switch (p) {
case 0:
return new ProfileFragment();
case 1:
return new LeaderBoardFragment();
case 2:
return new HomeFragment();
case 3:
return new ReferFragment();
case 4:
return new ProfileFragment();
default:
return new HomeFragment();
}
}
#Override
public int getItemCount() {
return 5;
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
this.viewPager2 = findViewById(R.id.vp_horizontal_ntb);
viewPager2.setOffscreenPageLimit(100);
this.bottomNavigationView = findViewById(R.id.navigation);
adapter = new ViewPagerAdapter(this);
viewPager2.setAdapter(adapter);
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
switch (position) {
case 0:
bottomNavigationView.getMenu().findItem(R.id.navigationMenu).setChecked(true);
break;
case 1:
bottomNavigationView.getMenu().findItem(R.id.navigationMyCourses).setChecked(true);
break;
case 2:
bottomNavigationView.getMenu().findItem(R.id.navigationHome).setChecked(true);
break;
case 3:
bottomNavigationView.getMenu().findItem(R.id.m_refer).setChecked(true);
break;
case 4:
bottomNavigationView.getMenu().findItem(R.id.navigationMyProfile).setChecked(true);
break;
}
}
});
bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
#SuppressLint("NonConstantResourceId")
#Override
public boolean onNavigationItemSelected(#NonNull #NotNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigationHome:
viewPager2.setCurrentItem(2);
break;
case R.id.navigationMyProfile:
viewPager2.setCurrentItem(4);
break;
case R.id.m_refer:
viewPager2.setCurrentItem(3);
break;
case R.id.navigationMyCourses:
viewPager2.setCurrentItem(1);
break;
case R.id.navigationMenu:
viewPager2.setCurrentItem(0);
break;
}
return false;
}
});
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) bottomNavigationView.getLayoutParams();
layoutParams.setBehavior(new BottomNavigationBehavior());
bottomNavigationView.setSelectedItemId(R.id.navigationMenu);
}
}
Happy Coding

java.lang.IllegalArgumentException: No view found for id 0x7f0d00c4

I want to pass some List from fragment into 2 other fragment. When i pass data to fragment two it is going well. But it is error when pass to the fragment three
Error code
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.yehezkiel.eclassapp, PID: 15267
java.lang.IllegalArgumentException: No view found for id 0x7f0d00c4 (com.example.yehezkiel.eclassapp:id/fragment3) for
fragment ThreeFragment{e045027 #3 id=0x7f0d00c4}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1415)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1752)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1821)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2595)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2382)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2337)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2244)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:702)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
Pass Code in OneFragment.java
Bundle bundle=new Bundle();
bundle.putStringArrayList("keys", keys);
//set Fragmentclass Arguments
Fragment fragobj=new TwoFragment();
fragobj.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frag2, fragobj).commitAllowingStateLoss();
Bundle bundle2=new Bundle();
bundle2.putStringArrayList("keys", keys);
//set Fragmentclass Arguments
Fragment fragobj2=new ThreeFragment();
fragobj2.setArguments(bundle2);
FragmentManager fragmentManager2 = getFragmentManager();
fragmentManager2.beginTransaction().replace(R.id.fragment3, fragobj2).commitAllowingStateLoss();
the first pass into TwoFragment did well. But the second pass gave me error like that. Please help me. I have been check all of the id in the ThreeFragment.xml and all correct.
ThreeFragment.java
package com.example.yehezkiel.eclassapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class ThreeFragment extends Fragment {
View v;
private List<DaftarPengumuman> listPengumuman = new ArrayList<>();
private ArrayList<String> obj3 = new ArrayList<>();
public ThreeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_three, container, false);
Bundle bundle = this.getArguments();
if(getArguments()!=null)
{
obj3 = bundle.getStringArrayList("keys");
Log.e("nba",obj3.toString());
}
// Inflate the layout for this fragment
return v;
}
}
fragment_three.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment3"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.yehezkiel.eclassapp.ThreeFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</FrameLayout>
This is my MainActivity.java that is stored the viewpager
package com.example.yehezkiel.eclassapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private List<MataKuliah> listMatkul = new ArrayList<>();
private ArrayList<String> keys = new ArrayList<>();
private myAdapter myAdapter;
private Button logoutBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener authListener;
private RecyclerView mRecycleView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
private NavigationView mNavigationView;
private TextView mTextName;
private TextView mTextNim;
private ProgressBar mProgressBar;
static {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users");
FirebaseUser users = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mataKuliahRef = FirebaseDatabase.getInstance().getReference("courses");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mAuth = FirebaseAuth.getInstance();
//Navbar menu
mToolbar = (Toolbar) findViewById(R.id.navbaraction);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawabel_main);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavigationView = (NavigationView) findViewById(R.id.nav_menu);
View header = mNavigationView.getHeaderView(0);
mTextName = (TextView) header.findViewById(R.id.header_name);
mTextNim = (TextView) header.findViewById(R.id.header_nim);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar2);
mProgressBar.setVisibility(View.VISIBLE);
//Tab Layout
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case (R.id.tugas):
break;
case (R.id.logout_menu):
signOut();
break;
}
return true;
}
});
userRef.child(users.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("name").getValue().toString();
String nim = (String) dataSnapshot.child("nim").getValue().toString();
mTextNim.setText(nim);
mTextName.setText(name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Beranda");
adapter.addFragment(new TwoFragment(), "Tugas");
adapter.addFragment(new ThreeFragment(), "Pengumuman");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void signOut() {
mAuth.signOut();
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(authListener);
}
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawabel_main"
tools:context="com.example.yehezkiel.eclassapp.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include
layout="#layout/navbar_action"
android:layout_width="match_parent"
android:layout_height="wrap_content"></include>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:tabGravity="fill"
app:tabMode="fixed" />
</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" />
<ProgressBar
android:id="#+id/progressBar2"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:visibility="visible"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="304dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/MainRView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="2dp"
android:layout_marginEnd="6dp"
android:layout_marginStart="6dp"
android:layout_marginTop="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/logoutBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="444dp"
android:background="#color/colorPrimary"
android:text="LOGOUT"
android:textColor="#color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.945"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navbar_main"
android:layout_gravity="start"
app:headerLayout="#layout/navbar_header"
android:id="#+id/nav_menu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

Nested ViewPager not refreshing

Problem Statement:
I have an activity on which I have used a view pager and inflated two fragments inside it.
The second fragment inside the view pager must also contain a view pager which has another fragment inside it(If you're wondering why this is a view pager if only a single fragment is required, because that is a configurable component and more fragments might be required inside it).
First Fragment
Second Fragment and the sub fragment inside it
Now, when we click a button I have to refresh the first and second fragments as well as the sub fragment( in the ViewPager) inside the second fragment.
The issue is that the first and the second fragments are getting updated but the sub fragment that is inside the view pager in the second fragment is not getting refreshed.
This happens after the click of the button:
First Fragment refreshed
Second fragment refreshed but the sub fragment did not
Tried solutions:
We tried to debug the code, tried clearing the adapters and the lists. Nothing worked.
Any pointers or suggestions welcome !
Code :
MainActivity.java
package com.example.admin.myapplication;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private GuestListPagerAdapter adapter;
private ViewPager viewPager;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.view_pager);
button = findViewById(R.id.button);
setUpViewPager();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.clearFragmentList();
adapter.addFragment(FirstFragment.newInstance("55"));
adapter.addFragment(SecondFragment.newInstance("88"));
adapter.notifyDataSetChanged();
}
});
}
private void setUpViewPager() {
if (null == adapter)
adapter = new GuestListPagerAdapter(getSupportFragmentManager());
adapter.addFragment(FirstFragment.newInstance("1"));
adapter.addFragment(SecondFragment.newInstance("2"));
viewPager.setAdapter(adapter);
}
public class GuestListPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
GuestListPagerAdapter(FragmentManager fm) {
super(fm);
}
void addFragment(Fragment fragment) {
mFragments.add(fragment);
}
void clearFragmentList(){
mFragments.clear();
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:weightSum="10"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"/>
<Button
android:text="Refresh View Pager"
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_gravity="center"/>
</LinearLayout>
SecondFragment.java
package com.example.admin.myapplication;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class SecondFragment extends Fragment {
private static final String TAG = SecondFragment.class.getSimpleName();
private static final String ARG_PARAM1 = "param1";
private String mParam1;
public SecondFragment() {
// Required empty public constructor
}
public static SecondFragment newInstance(String param1) {
SecondFragment fragment = new SecondFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
Log.d(TAG, "newInstance: 2F");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
Log.d(TAG, "onCreate: 2F");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_second, container, false);
TextView tv = (TextView) view.findViewById(R.id.tv2);
tv.setText(mParam1);
ViewPager pager = (ViewPager) view.findViewById(R.id.sub_view_pager);
SubListPagerAdapter adapter = new SubListPagerAdapter(getChildFragmentManager());
adapter.clearFragmentList();
adapter.addFragment(SubFragment.newInstance(mParam1));
pager.setAdapter(adapter);
Log.d(TAG, "onCreateView: 2F");
return view;
}
public class SubListPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
SubListPagerAdapter(FragmentManager fm) {
super(fm);
}
void addFragment(Fragment fragment) {
mFragments.add(fragment);
}
void clearFragmentList(){
mFragments.clear();
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
fragment_second.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="4"
tools:context=".SecondFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/tv2"
android:textSize="60sp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="#string/hello_blank_fragment" />
<android.support.v4.view.ViewPager
android:background="#color/colorAccent"
android:id="#+id/sub_view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"/>
</LinearLayout>
SubFragment.java
package com.example.admin.myapplication;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class SubFragment extends Fragment {
private static final String TAG = SubFragment.class.getSimpleName();
private static final String ARG_PARAM1 = "param1";
private String mParam1;
public SubFragment() {
// Required empty public constructor
}
public static SubFragment newInstance(String param1) {
SubFragment fragment = new SubFragment();
Bundle args = new Bundle();
if(fragment.getArguments()!=null)
fragment.getArguments().clear();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
Log.d(TAG, "newInstance: sub");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate: sub");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sub, container, false);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
TextView tv = (TextView) view.findViewById(R.id.sub_tv);
tv.setText(mParam1);
Log.d(TAG, "onCreateView: sub");
return view;
}
}
fragment_sub.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SubFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/sub_tv"
android:textSize="60dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_blank_fragment" />
</LinearLayout>
FirstFragment.java
package com.example.admin.myapplication;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class FirstFragment extends Fragment {
private static final String TAG = FirstFragment.class.getSimpleName();
private static final String ARG_PARAM1 = "param1";
private String mParam1;
public FirstFragment() {
// Required empty public constructor
}
public static FirstFragment newInstance(String param1) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
Log.d(TAG, "newInstance: 1F");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
Log.d(TAG, "onCreate: 1F");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText(mParam1);
Log.d(TAG, "onCreateView: 1F");
return view;
}
}
fragment_first.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FirstFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/tv"
android:textSize="60sp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>

error with java.lang.NullPointerException when trying to create table programically [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Okay I have spent hours trying to fix this, and no matter what I try I always get the same error, I assume I'm missing something stupidly easy so sorry if the question has already been answered I tried using their responses and it didn't help. All help is greatly appreciated.
I'm trying to add rows to a table programmatically, here is the code:
MainActivity.java:
package com.coreclue.random5;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableRow;
public class MainActivity extends AppCompatActivity{
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static Button b;
public static TableRow tr;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tr = new TableRow(this);
b = new Button(this);
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);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Snackbar.make(view, "test test test 123", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
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 tabView1 = inflater.inflate(R.layout.tab1, container, false);
View tabView2 = inflater.inflate(R.layout.tab2, container, false);
View tabView3 = inflater.inflate(R.layout.tab3, container, false);
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1){
tab1 obj = new tab1();
obj.main(tabView1);
return tabView1;
} else if(getArguments().getInt(ARG_SECTION_NUMBER) == 2){
tab2 obj = new tab2();
obj.main(tabView2);
return tabView2;
} else if(getArguments().getInt(ARG_SECTION_NUMBER) == 3){
return tabView3;
} else{
return tabView1;
}
}
}
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 3;
}
}
}
tab2.java where I want to code to lie that adds rows to table:
package com.coreclue.random5;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import static com.coreclue.random5.MainActivity.b;
public class tab2{
public static TableRow tr;
public void main(View rootView){
final TextView line1 = rootView.findViewById(R.id.line1);
line1.setText("aa");
TableLayout tl = (TableLayout) rootView.findViewById(R.id.table123);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
b.setText("Dynamic Button");
b.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
tr.addView(b);
tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
}
}
tab2.xml: where the table lies
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/table123"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:id="#+id/line1"
android:padding="3dip"
android:text="text 1" />
<TextView
android:gravity="right"
android:padding="3dip"
android:text="text 2" />
</TableRow>
<TableRow>
<TextView
android:padding="3dip"
android:text="text 3" />
<TextView
android:gravity="right"
android:padding="3dip"
android:text="text 4" />
</TableRow>
</TableLayout>
</LinearLayout>
</ScrollView>
and the error I get is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.coreclue.random5, PID: 21474
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TableRow.setLayoutParams(android.view.ViewGroup$LayoutParams)' on a null object reference
at com.coreclue.random5.tab2.main(tab2.java:31)
at com.coreclue.random5.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:106)
all I'm trying to get is a simple function where I can add as many rows to the table as needed, but just trying to add one row and it fails.
Finally solved it! in tab2.java line 10:
public static TableRow tr;
when I needed it to be:
import static com.coreclue.random5.MainActivity.tr;
I assume the var wasn't instantiated which is why I had the error.

Android tab clicked

I'm trying to apply TABs to my Android layout. How could I identify which tab was clicked?
I have an android tab layout made this way:
package com.truiton.designsupporttabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabFragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_2, container, false);
}
}
With the layout:
<?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"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab 2"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
I do not know how to identify that a tab like the above example was clicked.
Having as a principle that your code was based on the Truiton tutorial, just follow how they identify the clicks.
package com.truiton.designsupporttabs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
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:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment3 tab3 = new TabFragment3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
This should work!

Categories