I am using a view pager . I have three fragments in it I added a button in one of them and tried to make a method for it in the fragment class but this doesn't work. I tried after that to put the method in the main Activity class and it worked.
this is my MainActivity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(false);
mAuth = FirebaseAuth.getInstance();
mViewPager = findViewById(R.id.viewpager);
adapter = new SamplePagerAdapter(this);
tabLayout = findViewById(R.id.tablayout);
mViewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(1);
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("تعلم");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.learn, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText("الصفحة الرئيسية");
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabThree.setText("التحديات");
tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.challenges, 0, 0);
tabLayout.getTabAt(2).setCustomView(tabThree);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabPosition = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.myQuestions:
//newGame();
return true;
case R.id.aboutApp:
//showHelp();
return true;
case R.id.bestStudents:
//showHelp();
return true;
case R.id.myAccount:
//showHelp();
return true;
case R.id.signOut:
mAuth.signOut();
Intent i = new Intent(MainActivity.this, GeneralSignActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
if(tabPosition != 1){
mViewPager.setCurrentItem(1);
}
else{
this.finishAffinity();
System.exit(0);
}
}
}
and this is my fragment code :
public static LearnFragment newInstance(String param1, String param2) {
LearnFragment fragment = new LearnFragment();
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);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myView=inflater.inflate(R.layout.fragment_learn,container,false);
return myView;
}
And this is the xml code of the main activity :
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sample_main_layout"
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.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/color1">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/app_name"
android:textColor="#color/white"
android:textSize="#dimen/text_size_in_toolbar" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/color1">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
and this is the fragment xml code :
<?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="com.mk.playAndLearn.fragment.LearnFragment">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="click3"
android:text="click me"/>
</FrameLayout>
and tried to make a method for it in the fragment class but this
doesn't work
If you have added a Button to the Fragment, then you should initialize the Button inside the Fragment with the view prefix and adding the Button inside the Fragment layout too. So:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_learn,container,false);
Button myBtn = myView.findViewById(R.id.thebuttonid);
// use onClickListener here to handle the button
return myView;
}
I suppose you were handling the Button inside the MainActivity class which won't probably work.
You are handling the Button with onClick in the xml so, place the current code inside the Fragment and outside of onCreateView or any other methods:
public void click3(View v) {
switch(v.getId()) {
// do your stuff here
}
}
Related
how to open and close fragment while clicking on same button . Just like amazon filter button.
when we click first time fragment should apper and then we click on that button again fragment should disapper.
business activity java file
public class business extends AppCompatActivity {
TextView t1, t2;
Button hello;
boolean flag = false;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business);
hello = findViewById(R.id.hello);
t1=findViewById(R.id.text1);
t2=findViewById(R.id.textt2);
}
#Override
protected void onStart() {
super.onStart();
hello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getSupportFragmentManager();
BusinessSort businessSort = new BusinessSort();
fragmentTransaction = manager.beginTransaction();
if (flag) {
fragmentTransaction.remove(businessSort);
flag=false;
} else {
fragmentTransaction.add(R.id.frgmCont, businessSort);
flag=true;
}
fragmentTransaction.commit();
}
});
}
public void f1(String s1, String s2) {
t1.setText(s1);
t2.setText(s2);
}
}
activity_business.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"
tools:context=".business"
android:orientation="vertical"
android:id="#+id/businessLinearLayout">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hello"
android:id="#+id/hello"
/>
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="edit1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="edit2"
android:id="#+id/textt2"/>
<FrameLayout
android:id="#+id/frgmCont"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
Fagment file BusinessSort.java
public class BusinessSort extends Fragment {
EditText editText1,editText2;
Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =inflater.inflate(R.layout.fragment_business_sort, container, false);
editText1=view.findViewById(R.id.edit1);
editText2=view.findViewById(R.id.edit2);
submit=view.findViewById(R.id.businessfragment_submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1 = editText1.getText().toString();
String s2 = editText2.getText().toString();
business business = (com.example.project.business) getActivity();
business.f1(s1,s2);
}
});
return view;
}
fragment_business_sort.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=".BusinessSort"
android:orientation="vertical">
<EditText
android:id="#+id/edit1"
android:layout_width="match_parent"
android:layout_height="50dp"/>
<EditText
android:id="#+id/edit2"
android:layout_width="match_parent"
android:layout_height="50dp"/>
<Button
android:id="#+id/businessfragment_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SUBMIT"/>
</LinearLayout>
Try replacing the fragment.
fragmentTransaction.replace(R.id.frgmCont, businessSort);
flag = true;
I hope the code is mostly similar to my approach so let me know if the problem still persists so that I will look into it deeper.
public static boolean fragmentState = false;
onClick(){
if(fragmentState){
fragmentState = false;
getActivity().getFragmentManager().beginTransaction().
remove(SomeFragment.this).commit();
}
else{
fragmentState = true;
Fragment someFragment = new SomeFragment();
FragmentTransaction transaction =
getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, someFragment );
transaction.addToBackStack(null);
transaction.commit();
}
}
Please make sure that your button is not a part of that fragment.
You need to save the state of the fragment.
I created a TabbedActivity with some fragments, these fragments sometimes load and sometimes they dont, i've searched everywhere but couldn't find the issue.
Example gif
This is my main activity:
public class TwitterActivity extends AppCompatActivity implements MessagesFragment.OnFragmentInteractionListener, NotificationFragment.OnFragmentInteractionListener,
ProfileFragment.OnFragmentInteractionListener, TimeLineFragment.OnFragmentInteractionListener {
private static final String APP_TAG = "Twitter";
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
setContentView(R.layout.activity_twitter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
final TextView toolbarTitle = toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(3);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
if(position == 0){
toolbarTitle.setText(R.string.tab_timeline);
}else if(position == 1){
toolbarTitle.setText(R.string.tab_messages);
}else if(position == 2){
toolbarTitle.setText(R.string.tab_notifications);
}else if(position == 3){
toolbarTitle.setText(R.string.tab_profile);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) { }
#Override
public void onTabReselected(TabLayout.Tab tab) { }
});
tabLayout.setupWithViewPager(mViewPager, false);
}
#Override
public void onFragmentInteraction(Uri uri) { }
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.d(APP_TAG, String.valueOf(position));
if(position == 0){
return TimeLineFragment.newInstance();
}else if(position == 1){
return MessagesFragment.newInstance();
}else if(position == 2){
return NotificationFragment.newInstance();
}else if(position == 3){
return ProfileFragment.newInstance();
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return getString(R.string.tab_timeline);
case 1:
return getString(R.string.tab_messages);
case 2:
return getString(R.string.tab_notifications);
case 3:
return getString(R.string.tab_profile);
default:
return getString(R.string.tab_timeline);
}
}
}
}
This is one of my fragments (They are all the same):
public class TimeLineFragment extends Fragment {
private OnFragmentInteractionListener mListener;
public TimeLineFragment() {
}
public static TimeLineFragment newInstance() {
TimeLineFragment fragment = new TimeLineFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_time_line, 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 {
void onFragmentInteraction(Uri uri);
}
}
This is my main activity's layout file:
<?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=".activities.TwitterActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#mipmap/ic_launcher"
/>
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="#string/tab_timeline"
android:textSize="18sp"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:elevation="80dp"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="56dp"
app:tabGravity="fill"
app:tabIndicatorColor="#android:color/holo_orange_dark"
app:tabIndicatorHeight="0dp"
app:tabMode="fixed">
</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="100dp"
android:layout_above="#+id/tabs"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Please help me
EDIT: removed the useless TabItems.
You may have to use getChildFragmentManager() instead of getSupportFragmentManager() as parameter to create you adapter.
Here is error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.widget.Toolbar.setNavigationOnClickListener(android.view.View$
OnClickListener)' on a null object reference
it happen on
toolBar.setNavigationOnClickListener(new View.OnClickListener()
imageView.setOnClickListener(new View.OnClickListener()
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener()
have the same problem "null object reference".
my team separate file to fragment and all action listener in MainActivity is broke down but we want to separate to fragment like this, but I can't find why separate file to fragment it will null object reference
Here XML fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="56dp"
android:background="#color/colorPrimary"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteY="0dp"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<ImageView
android:id="#+id/pamba_icon_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="0dp"
app:layout_constraintLeft_toLeftOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/pambaicon"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
android:layout_marginBottom="0dp"
app:layout_constraintVertical_bias="0.0" />
<ImageView
android:id="#+id/filter_icon_id"
android:clickable="true"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginBottom="8dp"
android:layout_marginRight="48dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
app:layout_constraintRight_toRightOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="#+id/toolbar"
app:srcCompat="#drawable/filter"
app:layout_constraintVertical_bias="0.533" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPaper_id"
android:layout_below="#id/toolbar">
</android.support.v4.view.ViewPager>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottomNavigation_id"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottom_navigation_menu"
app:theme="#style/BottomNavigationTheme"
app:itemBackground="#color/colorGray"/>
</android.support.design.widget.CoordinatorLayout>
</android.support.constraint.ConstraintLayout>
Here activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.constraint.ConstraintLayout
android:id="#+id/contentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
Here MainFragment
import...
public class MainFragment extends Fragment {
public MainFragment() {
super();
}
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
initInstances(rootView);
return rootView;
}
private void initInstances(View rootView) {
// Init 'View' instance(s) with rootView.findViewById here
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
/*
* Save Instance State Here
*/
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save Instance State here
}
/*
* Restore Instance State Here
*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore Instance State here
}
}
}
and MainActivity
import...
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
Toolbar toolBar;
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView imageView;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
setTitle(R.string.title);
drawerLayout = (DrawerLayout) findViewById(R.id.drawe_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
imageView = (ImageView) findViewById(R.id.filter_icon_id);
navigationView.setNavigationItemSelectedListener(this);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolBar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
// set own toolbar
toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
toolBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
drawerLayout.closeDrawer(Gravity.RIGHT);
} else {
drawerLayout.openDrawer(Gravity.RIGHT);
}
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "filter click", Toast.LENGTH_SHORT).show();
}
});
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigation_id);
// select item from bottom navigation
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.firstpage_id:
Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_SHORT).show();
break;
case R.id.offergape_id:
Toast.makeText(getApplicationContext(), "offer", Toast.LENGTH_SHORT).show();
break;
case R.id.needpage_id:
Toast.makeText(getApplicationContext(), "need", Toast.LENGTH_SHORT).show();
break;
case R.id.searchpage_id:
Toast.makeText(getApplicationContext(), "search", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
}
//close drawer when click back
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.END)){
drawerLayout.closeDrawer(GravityCompat.END);
}else {
super.onBackPressed();
}
}
// select item from drawer
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.account_detail_id:
Toast.makeText(getApplicationContext(), "account", Toast.LENGTH_SHORT).show();
break;
case R.id.trip_detail_id:
Toast.makeText(getApplicationContext(), "detail", Toast.LENGTH_SHORT).show();
break;
case R.id.mail_id:
Toast.makeText(getApplicationContext(), "mail", Toast.LENGTH_SHORT).show();
break;
case R.id.logout_id:
Toast.makeText(getApplicationContext(), "logout", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.END);
return true;
}
}
edit add navigation_drawer.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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawe_layout"
android:fitsSystemWindows="true"
tools:openDrawer="end">
<!--set drawer open from right-->
<include layout="#layout/activity_main"/>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/navigation_view"
android:background="#color/colorGray"
android:fitsSystemWindows="true"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/navigation_menu"
app:theme="#style/NavigationDrawerStyle"
android:layout_gravity="end"/>
<!--set drawer open from right-->
</android.support.v4.widget.DrawerLayout>
Your setContentView in onCreate is setting it to R.layout.navigation_drawer. You didn't provide an example of that, but instead provided an example of R.layout.fragment_main. I'm thinking you want that one to be your layout instead. So in onCreate in your activity set your content view to that layout instead:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
... // The rest of your code here
}
I've implemented TabLayout from the support library, but it overwrites the ActionBar that i need.
This is the activity that sets it up and inflates the tabs and loads the fragment for the tab.
public class TabsActivity extends android.support.v4.app.FragmentActivity {
FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
setTitle("Fuel Logger");
ActionBar a = getActionBar();
ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
vp.setAdapter(new FragmentPagerAdapter(
getSupportFragmentManager(), TabsActivity.this
));
TabLayout tabLayout = (TabLayout) findViewById(R.id.fuel_sliding_tabs);
tabLayout.setupWithViewPager(vp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.fuel_menu, menu);
MenuItem refresh = menu.findItem(R.id.action_settings);
refresh.setEnabled(true);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_settings:
break;
case R.id.action_favorite:
return true;
default:
}
return super.onOptionsItemSelected(item);
}
}
and the xml is just the view pager and tab layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<android.support.design.widget.TabLayout
style="#style/FuelTabLayout"
android:id="#+id/fuel_sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1.27"
android:background="#android:color/white"
android:layout_alignParentBottom="true"
android:layout_below="#+id/fuel_sliding_tabs" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#android:drawable/ic_menu_set_as"
app:layout_anchorGravity="bottom|right|end"
app:backgroundTint="#color/colorAccent"
android:layout_gravity="right"
android:cropToPadding="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp" />
</RelativeLayout>
and an example of fragments code which is more or less the same for each fragments class
Public class SummaryFragment extends android.support.v4.app.Fragment {
public static final String ARG_PAGE = "SUMM_PAGE";
private int mTab;
public static SummaryFragment newInstance(int page){
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
SummaryFragment frag = new SummaryFragment();
frag.setArguments(args);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTab = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_summary, null);
return view;
}
first add ToolBar , and use LinearLayout witch have horizontal orientation
and set the in the style NoActionBar
hope its help you
I am trying to dynamically change a text from a fragment textview inside de activity but I keep getting 'cannot obtain root' error. I tried to instantiate the textview inside onCreateView and inside onActivityCreated as well but it doesnt work. How can I change the text from a fragment textview inside the activity?
Fragment xml:
<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 1"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
Fragment Code:
public class TabFragment1 extends Fragment {
private TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv = (TextView) getView().findViewById(R.id.textView);
}
public void setText(String text){
tv.setText(text);
}
}
Main xml:
<RelativeLayout
android:id="#+id/main_layout"
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"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
Main code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
TabFragment1 t1 = new TabFragment1();
TabFragment2 t2 = new TabFragment2();
TabFragment3 t3 = new TabFragment3();
adapter.newFrag(t1);
adapter.newFrag(t2);
adapter.newFrag(t3);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
t1.setText("HELLO WORLD");
}
#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);
}
}
PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
List<Fragment> aFrag;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
aFrag = new ArrayList<Fragment>();
}
public void newFrag(Fragment f){
aFrag.add(f);
}
#Override
public Fragment getItem(int position) {
return aFrag.get(position);
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
You try to set text on view, but this view wasn't created, this fragment wasn't created. If You want to set text from activity you can pass bundle to fragment arguments with that text, and in fragment chceck bundle and set text. Later if you want to change text in this fragment then you can use your function.
public class TabFragment1 extends Fragment {
private TextView tv;
public static TabFragment1 create(String text){
Bundle b = new Bundle();
b.putString("textdata",text);
TabFragment1 f = new TabFragment1();
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
tv = (TextView) view.findViewById(R.id.textView);
if(getArguments()!=null){
tv.setText(getArguments().getString("textdata"));
}
return view;
}
public void setText(String text){
tv.setText(text);
}
}
In your activity create this fragment using static method:
TabFragment1 t1 =TabFragment1.create("HELLO WORLD");
Hardcore execution of your base code is:
new Handler().postDelayed(new Runnable(){t1.setText("HELLO WORLD");},300);