I create a project with the NavigationDrawerFragment, and I set the fragments for the menu. Switching between menus fragments are working. But now I create an imageview on one of the fragments. and I want that when you click on the imageview it changes fragment just like the menu.
MainActivity.java
package com.****.****;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new news_Fragment();
break;
case 1:
objFragment = new heroes_Fragment();
break;
case 2:
objFragment = new game_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* 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;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
heroes_Fragment.java
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
public View trac(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
}
heroes_layout.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"
android:background="#drawable/header_bg">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignWithParentIfMissing="false"
android:id="#+id/tableLayout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/icontrac"
android:src="#drawable/icon_portrait_trac"
android:layout_column="0"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:clickable="true"
android:onClick="trac"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/iconreap"
android:src="#drawable/icon_portrait_reap"
android:layout_column="1"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/iconwid"
android:src="#drawable/icon_portrait_wid"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</TableRow>
</TableLayout>
</RelativeLayout>
trac_Fragment.java
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class trac_Fragment extends Fragment {
}
}
I want that when you click on the imageview (trac) it changes fragment. As if we change activity.
And sorry for my English.
I tried to use trac() methode but the apps crash
You did set in layout android:onClick="trac", but you never used trac() method.
You should declare trac() {...} under appropriate class (where you implement that heroes_layout.xml), and resolve call of new activity there (using Intents)
Thanks Gudin for your help. You really help me. Fragment are very complex to understand. I solved my problem.
package com.****.****;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment implements OnClickListener{
Button btnChange;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.heroes_layout, container, false);
ImageButton btntrac = (ImageButton) view.findViewById(R.id.icontrac);
btntrac.setOnClickListener(this);
return view;
}
public void onClick(View v) {
trac(v);
}
android.support.v4.app.FragmentManager manager;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
manager=getFragmentManager();
}
public void trac(View view) {
android.support.v4.app.FragmentTransaction transaction =manager.beginTransaction();
transaction.replace(R.id.container,new trac_Fragment());
transaction.addToBackStack(null);
transaction.commit();
}
}
This is working.
Related
I am trying to set a tab layout inside a fragment and call it by an option inside navigation drawer but I am getting a null object reference error.
I am setting my navigation drawer inside Main2Activity
Main2Activity
import android.content.Intent;
import android.os.Bundle;
import com.bumptech.glide.Glide;
import com.example.fireapp.model.Users;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Layout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.example.fireapp.ui.main.SectionsPagerAdapter;
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 de.hdodenhof.circleimageview.CircleImageView;
public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private View headerView;
private TextView usernameText;
private TextView emailText;
private CircleImageView userImage;
private FirebaseUser firebaseUser;
private DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("fireApp");
//navigation drawer
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
//user details
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
headerView = navigationView.getHeaderView(0);
usernameText = headerView.findViewById(R.id.usernameText);
userImage = headerView.findViewById(R.id.userImage);
emailText = headerView.findViewById(R.id.userEmail);
setUserDetails();
// if(savedInstanceState==null) {
// getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
// new chatFragment()).commit();
// navigationView.setCheckedItem(R.id.nav_chat);
// }
}
private void setUserDetails() {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("User").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users user = dataSnapshot.getValue(Users.class);
usernameText.setText(user.getUsername());
emailText.setText(firebaseUser.getEmail());
if (user.getImageUrl().equals("default")) {
userImage.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(getApplicationContext()).load(user.getImageUrl()).into(userImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.nav_chat:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new chatFragment()).commit();
break;
case R.id.nav_share:
Toast.makeText(this, "Share!", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_feedback:
Toast.makeText(this, "Feedback!", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//3 dots menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.logout) {
AuthUI.getInstance()
.signOut(Main2Activity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(Main2Activity.this, MainActivity.class));
finish();
}
});
return true;
} else
return false;
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".Main2Activity"
tools:openDrawer="end">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer_menu"></com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
chatFragment
package com.example.fireapp;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.fireapp.ui.main.SectionsPagerAdapter;
import com.google.android.material.tabs.TabLayout;
public class chatFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_chat,container,false);
tabLayout=view.findViewById(R.id.tabs);
viewPager=view.findViewById(R.id.view_pager);
viewPager.setAdapter(new SectionsPagerAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
}
fragment_chat.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".chatFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</FrameLayout>
SectionPagerAdapter
package com.example.fireapp.ui.main;
import android.content.Context;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.fireapp.R;
import com.example.fireapp.tab1;
import com.example.fireapp.tab2;
import com.example.fireapp.tab3;
import java.util.List;
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2,R.string.tab_text_3};
private Context mContext ;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
public SectionsPagerAdapter(FragmentManager childFragmentManager) {
super(childFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0 :
tab1 tab1 = new tab1();
return tab1;
case 1:
tab2 tab2 = new tab2();
return tab2;
case 2:
tab3 tab3 = new tab3();
return tab3;
}
return null;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
I am getting the following error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fireapp, PID: 6785
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at com.example.fireapp.ui.main.SectionsPagerAdapter.getPageTitle(SectionsPagerAdapter.java:61)
at com.google.android.material.tabs.TabLayout.populateFromPagerAdapter(TabLayout.java:1323)
at com.google.android.material.tabs.TabLayout.setPagerAdapter(TabLayout.java:1314)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1227)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1188)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1168)
at com.example.fireapp.chatFragment$1.run(chatFragment.java:32)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
I am new to android development please help.
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()'
on a null object reference
NullPointerException is thrown when an application attempts to use an object reference that has the null value.
You can try with this
private String TAB_TITLES[] = new String[]{"Tab1", "Tab2", "Tab3"};
Then
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return TAB_TITLES[position];
}
getPageTitle() - This method may be called by the ViewPager to obtain a title string to describe the specified page.
I am trying to replace home fragment with gallery fragment and vice versa in the default navigation drawer from Android Studio. This is the main class:
package com.example.navdrawer;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
This is the home fragment class:
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.navdrawer.R;
import com.example.navdrawer.ui.gallery.GalleryFragment;
public class HomeFragment extends Fragment {
Button button;
TextView textView = null;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
textView = root.findViewById(R.id.text_home);
textView.setText("This is home fragment");
button = root.findViewById(R.id.home_button);
return root;
}
public void onClick(View v) {
//respond to clicks
if (v.getId() == R.id.home_button) {
GalleryFragment frag = new GalleryFragment();
FragmentManager ft = getFragmentManager();
FragmentTransaction fragmentTransaction =ft.beginTransaction();
fragmentTransaction.replace(R.id.home, frag);
// ft.addToBackStack(null);
fragmentTransaction.commit();
}
}
}
The gallery fragment is simillar with the home fragment:
package com.example.navdrawer.ui.gallery;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.navdrawer.R;
import com.example.navdrawer.ui.home.HomeFragment;
public class GalleryFragment extends Fragment {
Button button;
TextView textView = null;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
textView = root.findViewById(R.id.text_gallery);
textView.setText("This is gallery fragment");
button = root.findViewById(R.id.gallery_button);
return root;
}
public void onClick(View v) {
//respond to clicks
if (v.getId() == R.id.gallery_button) {
HomeFragment frag = new HomeFragment();
FragmentManager ft = getFragmentManager();
FragmentTransaction fragmentTransaction =ft.beginTransaction();
fragmentTransaction.replace(R.id.gallery, frag);
// ft.addToBackStack(null);
fragmentTransaction.commit();
}
}
}
And I've got this xml for the home fragment, which is simillar with the xml from the gallery fragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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/scrollView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
android:id="#+id/home"
android:screenOrientation="portrait"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_home"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/home_button"
android:layout_centerHorizontal="true"
android:layout_below="#+id/text_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/replace1" />
</RelativeLayout>
</ScrollView>
I don't know why it's not working.
I've found the answer from this post: link
For navigation between fragments, all I had to do was to implement this method in the "onCreateView" function:
button.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.nav_gallery, null));
Another method is:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Navigation.findNavController(view).navigate(R.id.nav_gallery);
}
});
I still don't know how to navigate between fragments using a conditional "if, else" statement, inside a function, maybe this will imply another type of "action listening"...
The default template uses the Navigation component which means you don't manually do FragmentTransactions. Instead, as per the documentation, you'd add your GalleryFragment to your navigation XML file (under res/navigation) then call navigate() to go to that destination, replacing the screen you're currently on.
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>
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!
I'm using fragment tab.
I need the webView to refresh to the original url when user clicks on the title.
This is my code for now.
MainActivity.java
package com.cn1304w.munch;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#fff"
android:paddingBottom="10dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="10dp"
android:textColor="#000" />
</android.support.v4.view.ViewPager>
ViewPagerAdapter.java
package com.cn1304w.munch;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
// Tab Titles
private String tabtitles[] = new String[] { "Home", "Search", "Profile" };
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
// Open FragmentTab3.java
case 2:
FragmentTab3 fragmenttab3 = new FragmentTab3();
return fragmenttab3;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
fragmenttab1.java
package com.cn1304w.munch;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class FragmentTab1 extends Fragment {
WebView webView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// get the url to open
// set up the WebView
webView = (WebView) getView().findViewById(R.id.webView);
webView.setWebViewClient(new MyBrowser());
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.loadUrl("http://192.168.1.4/index.html");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.fragmenttab1, container, false);
return view;
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
fragmenttab1.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" >
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</RelativeLayout>
Use this functionality when ever you need to refresh your webview.
ourActivity.this.webView.loadUrl("http://www.mysite.php");