Using a progressBar in a listview item - android-fragments

I have this listview and it's coded in a fragment class. When selecting a listview item it goes to another fragment and displays the details . But it takes several seconds to load the data because the data i display is using AsyncTask,so it takes some time to get data from the JSON and display . So i need to use a progressBar when an item is clicked in the listview and it should close when the data is ready to display. How can i do this? I referred several tutorials and tried many of them. But i couldn't accomplish what i'm looking for.Hope some of you can help me.
NewsFragment class
private ListView listView;
private ArrayList<BaseElement> News;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.news_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
listView = (ListView) view.findViewById(R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id){
android.support.v4.app.Fragment detail = new NewsDetailFragment();
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.content_frame, detail).addToBackStack("back").commit();
}
});
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
News = JSONServices.getNewsDescription();
return null;
}
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setNewsDescription(News);
adapter = new LazyAdapter(News, activity,Element.NEWS_LIST.getType());
listView.setAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
}
NewsDetailFragment
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
}
NewsList layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/grey"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#drawable/listview" >
<ImageView
android:id="#+id/thumb_image"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
/>
<TextView
android:id="#+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_toRightOf="#+id/thumb_image"
android:layout_marginTop="10dp"
android:layout_marginLeft="7dp"
android:textStyle="bold"
android:textSize="20dp" />
<!-- <TextView
android:id="#+id/news_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textStyle="bold"
android:layout_below="#+id/news_title"
android:textSize="15dp" /> -->
</LinearLayout>
</RelativeLayout>
NewsFragment layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/grey" >
<!-- <GridView
android:id="#+id/gridView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="2"
android:stretchMode="columnWidth"
android:layout_margin="5dp"
android:columnWidth="100dp"/> -->
<ListView
android:id="#+id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:dividerHeight="10dp"
android:layout_margin="6dp">
</ListView>
</LinearLayout>

Add ProgressBar to your NewsFragment layout:
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:indeterminate="true"
android:visibility="gone" />
Then in onItemClick method change it's visibility to true progressBar.setVisibility(View.VISIBLE) to show it and change it's visibility to false to hide it progressBar.setVisibility(View.GONE) in onPostExecute of AsyncTask.

Ok i got it now. I modified my 2nd fragment like this. When an item in the listview is clicked it goes to my second class.So i added a progressBar to my second class and it worked!
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
private ProgressDialog dialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
dialog = new ProgressDialog(NewsDetailFragment.this.getActivity());
dialog.setMessage("Loading News");
dialog.setCancelable(true);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.show();
super.onPreExecute();
}
}
}

Related

IllegalStateException : Activity has been destroyed . I created fragment manager in adapter class on click view

I created recycler view and perform onclick action to get fragment view. when I click on item it should show same data in fragment so I created an on click listener in Adapter class(onBindViewHolder).
package com.example.
public class Adapter extends
RecyclerView. Adapter<ChannelAdapter.ChannelViewHolder> {
private final Context context;
private List<ChannelMode> ;
public Channel Adapter(Context context, List<ChannelModel> channelList) {
this.context = context;
this.channelList = channelList;
}
#Override
public ChannelViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.layout_view, parent, false);
return new ChannelViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ChannelViewHolder holder, final int position) {
final ChannelModel channelModel = channelList.get(position);
holder.channel_name.setText(channelModel.getChannel_name());
holder.description.setText(channelModel.getDescription());
Picasso.get().load(channelModel.getLogo()).into(holder.logo);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked", Toast.LENGTH_LONG).show();
Fragment fragment = new FragmentView();
AppCompatActivity activity = new AppCompatActivity();
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.framelayout, fragment).addToBackStack(null);
fragmentTransaction.commit();
}
});
}
#Override
public int getItemCount() {
return channelList.size();
}
public class ChannelViewHolder extends RecyclerView.ViewHolder {
ImageView logo;
TextView channel_name;
TextView description;
public ChannelViewHolder(#NonNull final View itemView) {
super(itemView);
logo = itemView.findViewById(R.id.imageView);
channel_name = itemView.findViewById(R.id.textViewName);
description = itemView.findViewById(R.id.textViewDesc);
}
}
}
<FrameLayout
android:id="#+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="#+id/recyclerView" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Fragment view when I click on recyclerview item.

Blank screen when trying to implement MVVM / ViewModel and data binding architecture

I am trying to implement the Model-View-ViewModel architectural pattern and XML data binding in my Android Java app. The code seems all correct as far as I can see, however I'm getting a blank screen when I run the app (not even the bottomNavigationView is showing). I am using a ViewModel to store/persist data for a fragment called AllTimeBestFragment. Specifically, AllTimeBestFragment is one of three fragments in a Viewpager-tabLayout.
Would appreciated any insight into what I'm doing wrong!
AllTimeBestFragment
public class AllTimeBestFragment extends Fragment {
private ImageViewCallback imageViewCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(Constants.SkiCompanionDebug, "AllTimeBestFragment");
bindToViewModel();
return inflater.inflate(R.layout.fragment_all_time_best, container, false);
}
//imageview callback
#Override
public void setUserVisibleHint(boolean visible) {
super.setUserVisibleHint(visible);
imageViewCallback.setImage(R.drawable.all_time_best);
}
public void addCallback(ImageViewCallback imageViewCallback) {
this.imageViewCallback = imageViewCallback;
}
//binding the view (fragment) to the asoociated viewModel
public void bindToViewModel(){
FragmentAllTimeBestBinding binding = DataBindingUtil.setContentView(getActivity(), R.layout.fragment_all_time_best);
AllTimeBestViewModel viewModel = ViewModelProviders.of(this).get(AllTimeBestViewModel.class);
AllTimeStats allTimeStats = BCCDatabase.getInstance(getActivity()).getAllTimeStats();
viewModel.init(allTimeStats);
binding.setAllTimeBestViewModel(viewModel);
}
}
AllTimeBestViewModel
public class AllTimeBestViewModel extends ViewModel {
private AllTimeStats allTimeStats;
public void init(AllTimeStats allTimeStats) {
this.allTimeStats = allTimeStats;
}
public String getDurationTotal(){
return ""+allTimeStats.getDurationTotal();
}
}
fragment_all_time_best.xml
<data>
<variable
name="allTimeBestViewModel"
type="skicompanion.skicompanion.viewmodels.AllTimeBestViewModel" />
</data>
<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/track_scrollview"
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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="skicompanion.skicompanion.fragments.AllTimeBestFragment">
<android.support.v7.widget.CardView
android:id="#+id/duration_cardview"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/duration_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{allTimeBestViewModel.durationTotal}"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="#+id/duration_total_tv"
app:layout_constraintStart_toStartOf="#+id/imageView2"
app:layout_constraintTop_toBottomOf="#+id/duration_total_tv" />
...
...
...
Gradle
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "android.arch.lifecycle:viewmodel:1.1.1"
I found the answer here: How to use data-binding with Fragment
I was binding the data as if I were dealing with an activity - I needed to bind it for a fragment instead. The trick was to use DataBindingUtil.inflate rather than DataBindingUtil.setContentView. Below is the correct code snippet:
public class AllTimeBestFragment extends Fragment {
private ImageViewCallback imageViewCallback;
private FragmentAllTimeBestBinding binding;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(Constants.SkiCompanionDebug, "AllTimeBestFragment");
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_all_time_best, container, false);
bindToViewModel();
return binding.getRoot();
}
//imageview callback
#Override
public void setUserVisibleHint(boolean visible) {
super.setUserVisibleHint(visible);
imageViewCallback.setImage(R.drawable.all_time_best);
}
public void addCallback(ImageViewCallback imageViewCallback) {
this.imageViewCallback = imageViewCallback;
}
//binding the view (fragment) to the asoociated viewModel
public void bindToViewModel(){
AllTimeBestViewModel viewModel = ViewModelProviders.of(this).get(AllTimeBestViewModel.class);
AllTimeStats allTimeStats = BCCDatabase.getInstance(getActivity()).getAllTimeStats();
viewModel.init(allTimeStats);
binding.setAllTimeBestViewModel(viewModel);
}
}

Working with fragments - findViewById returns NULL on Button in Android

I've started dealing with Fragments in Android. I created Activity with NavigationView which has 3 items and worked with 3 simple fragments till now. NavigationHeader has 2 buttons - 1 starts LoginActivity and 2nd RegisterActivity. I remind that everything till niw worked fine. Today I've tried to create RecyclerView inside one of the fragments. Now when I try to run app, findViewById applied to those 2 NavigationHeader buttons returns NULL. I have no idea why.
Here is HomeActivity:
public class HomeActivity extends AppCompatActivity {
private static final String FRAGMENT_POSITION = "fragment_position"; // Fragment Position
private DrawerLayout mDrawerLayout; // NavigationDrawer Layout
private NavigationView nvDrawer; // NavigationView
private CoordinatorLayout homeCoordinatorLayout; // Coordinator Layout For Snackbar
private Toolbar toolbar; // Application Toolbar
private TextView navHeaderNamePlusSurname; // Name And Surname Navigation Header Text
private TextView navHeaderEmail; // E-mail Navigation Header Text
AppCompatButton navHeaderButtonLogin; // Login/Logout Button
AppCompatButton navHeaderButtonRegister; // Register Button
private ActionBarDrawerToggle mDrawerToggle; // ActionBar Drawer Toggle
private SQLiteHandler db; // SQLite Database Helper Class
private SessionManager session; // Session Manager
private int lastShownFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Setting Toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// Setting Up DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = setupDrawerToggle();
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Navigation Header Logout Button
navHeaderButtonLogin = (AppCompatButton) findViewById(R.id.nav_header_btn_log_in_out);
navHeaderButtonRegister = (AppCompatButton) findViewById(R.id.nav_header_btn_register);
Log.d("czy_null", "navHeaderButtonLogin: " + navHeaderButtonLogin + ", navHeaderButtonRegister: " + navHeaderButtonRegister);
// Name, Surname And E-mail Texts
navHeaderNamePlusSurname = (TextView) findViewById(R.id.nav_header_name_plus_surname);
navHeaderEmail = (TextView) findViewById(R.id.nav_header_email);
// SQLite Database Handler
db = new SQLiteHandler(getApplicationContext());
// Session Manager
session = new SessionManager(getApplicationContext());
// Navigation Drawer
nvDrawer = (NavigationView) findViewById(R.id.navigation_view);
// Checking If User Is Logged In
if (!session.isLoggedIn()) {
hideNavigationViewGroup(nvDrawer); // Hiding NavigationView Group Depending
// If Not Logged
} else {
navHeaderButtonLogin.setText(getText(R.string.home_btn_log_out));
navHeaderButtonRegister.setVisibility(View.INVISIBLE);
// Fetching User Details From SQLite
HashMap<String, String> user = db.getUserDetails();
String name = user.get(SQLiteHandler.KEY_NAME);
String surname = user.get(SQLiteHandler.KEY_SURNAME);
String email = user.get(SQLiteHandler.KEY_EMAIL);
// Setting Navigation Header Texts
String nameSurname = name + " " + surname;
navHeaderNamePlusSurname.setText(nameSurname);
navHeaderEmail.setText(email);
}
// Setting Up CoordinatorLayout
homeCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.home_coordinator_layout);
// Setting Listener To NavigationView
setupDrawerContent(nvDrawer);
// Setting Starting Fragment
if (savedInstanceState == null) {
setStartingFragment();
} else {
restoreOnInstanceState(savedInstanceState.getInt(FRAGMENT_POSITION));
}
// Applying Login/Logout Button Listener
setLoginButtonListener();
// Applying Register Button Listener
setRegisterButtonListener();
}
// Listener To Login/Register Button
private void setLoginButtonListener() {
navHeaderButtonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!session.isLoggedIn()) {
mDrawerLayout.closeDrawers();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
} else {
mDrawerLayout.closeDrawers();
logoutUser();
navHeaderNamePlusSurname.setText(getString(R.string.nav_header_name_surname));
navHeaderEmail.setText(getString(R.string.nav_header_email));
hideNavigationViewGroup(nvDrawer);
navHeaderButtonLogin.setText(getString(R.string.home_btn_log_in));
navHeaderButtonRegister.setVisibility(View.VISIBLE);
showSnackbarInfo(getString(R.string.inf_logout_success),
R.color.snackbar_success_msg);
}
}
});
}
// Listener To Register Button
private void setRegisterButtonListener() {
navHeaderButtonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.closeDrawers();
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
startActivity(intent);
}
});
}
// Logging Out The User
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
}
// Setting Up DrawerToggle
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open,
R.string.drawer_close);
}
// Setting Up Drawer Content
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
// Replace Existing Fragment With a New One
public void selectDrawerItem(MenuItem menuItem) {
Fragment fragment = null;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_top20_recipes: {
fragmentClass = Top20RecipesFragment.class;
lastShownFragment = 0;
break;
}
case R.id.nav_kitchen_type: {
fragmentClass = KitchenTypeFragment.class;
lastShownFragment = 1;
break;
}
case R.id.nav_meal_type: {
fragmentClass = MealTypeFragment.class;
lastShownFragment = 2;
break;
}
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle()); // Updating Toolbar Title
mDrawerLayout.closeDrawers(); // Close The Drawer
}
// Function Setting First Fragment
private void setStartingFragment() {
Fragment fragment = null;
Class fragmentClass = Top20RecipesFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
lastShownFragment = 0;
MenuItem menuItem = nvDrawer.getMenu().getItem(0);
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle()); // Updating Toolbar Title
}
// Saving Fragment Title State
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(FRAGMENT_POSITION, lastShownFragment);
}
// Restoring Fragment Title States
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
restoreOnInstanceState(savedInstanceState.getInt(FRAGMENT_POSITION));
}
// Restoring Selected Item On Screen Rotation Or App Minimalize
private void restoreOnInstanceState(int lastPosition) {
Fragment fragment = null;
Class fragmentClass = null;
switch (lastShownFragment) {
case 0: {
fragmentClass = Top20RecipesFragment.class;
break;
}
case 1: {
fragmentClass = KitchenTypeFragment.class;
break;
}
case 2: {
fragmentClass = MealTypeFragment.class;
break;
}
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
lastShownFragment = lastPosition;
MenuItem menuItem = nvDrawer.getMenu().getItem(lastPosition);
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Function Hiding Items In NavigationView
private void hideNavigationViewGroup(NavigationView nvDrawer) {
nvDrawer.getMenu().setGroupVisible(R.id.nav_group_logged_user, false);
}
// Function Showing Snakcbar
private void showSnackbarInfo(String info, int textColor) {
Snackbar snackbar = Snackbar.make(homeCoordinatorLayout, info, Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView sbText = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
sbText.setTextColor(ContextCompat.getColor(getApplicationContext(), textColor));
snackbar.show();
}
}
Here is my fragment which has to contain RacyclerView:
public class KitchenTypeFragment extends Fragment {
RecyclerView kitchenTypeRecycleView;
private ArrayList<KitchenTypeItem> kitchenTypeItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
kitchenTypeItems = new ArrayList<>();
fillKitchenTypeArray(kitchenTypeItems);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_kitchen_type, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
kitchenTypeRecycleView = (RecyclerView) view.findViewById(R.id.kitchen_type_recycle_view);
kitchenTypeRecycleView.setHasFixedSize(true);
kitchenTypeRecycleView.setAdapter(new KitchenTypeAdapter(kitchenTypeItems,
R.layout.kitchen_type_grid_item));
kitchenTypeRecycleView.setLayoutManager(new GridLayoutManager(getContext(), 2));
kitchenTypeRecycleView.setItemAnimator(new DefaultItemAnimator());
}
private void fillKitchenTypeArray( ArrayList<KitchenTypeItem> kitchenTypeItems) {
KitchenTypeItem kitchenItem;
// Currently 8 Kitchen Types
String[] itemNames = getResources().getStringArray(R.array.kitchen_types);
// Filling ArrayList
for(int i = 0; i < itemNames.length; i++) {
kitchenItem = new KitchenTypeItem(itemNames[i], R.drawable.example_kitchen_type);
kitchenTypeItems.add(kitchenItem);
}
}
}
Here is XML from HomeActivity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/home_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RegisterActivity">
<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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".SignUpActivity">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/frame_layout_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header" />
</android.support.v4.widget.DrawerLayout>
</android.support.design.widget.CoordinatorLayout>
Here is NavigationHeader XML with those 2 buttons:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relative_nav_header"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="192dp"
android:background="#color/primary"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
android:paddingTop="40dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:orientation="vertical">
<!-- Name + Surname, E-mail -->
<LinearLayout
android:id="#+id/nav_lin_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|left"
android:orientation="vertical">
<!-- Name + Surname Text -->
<TextView
android:id="#+id/nav_header_name_plus_surname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:textSize="17sp"
android:text="#string/nav_header_name_surname" />
<!-- E-mail Adress -->
<TextView
android:id="#+id/nav_header_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/accent"
android:fontFamily="sans-serif"
android:textSize="13sp"
android:text="#string/nav_header_email" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="7dp"
android:gravity="center|left"
android:layout_below="#+id/nav_lin_layout">
<!-- Login/Logut Button -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/nav_header_btn_log_in_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:backgroundTint="#color/nav_header_login_color"
android:textColor="#color/text_icons"
android:stateListAnimator="#null"
android:text="#string/btn_log_in" />
<android.support.v7.widget.AppCompatButton
android:id="#+id/nav_header_btn_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:backgroundTint="#color/nav_header_register_color"
android:stateListAnimator="#null"
android:textColor="#color/text_icons"
android:text="#string/btn_sign_up" />
</LinearLayout>
</RelativeLayout>
And here is finally XML from Fragment:
<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"
android:id="#+id/kitchen_type_fragment"
android:padding="16dp"
tools:context="com.example.nazwamarki.myapplication.fragments.KitchenTypeFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/kitchen_type_recycle_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
You should use findViewById on the headerView like this:
navigationView.getHeaderView(0).findViewById()

How to load a fragment view in a tab

I am trying to create tabs inside a fragment. I manage to create tab inside the fragment, but now I want to load different fragment for each tab (fragment1.class and fragment2.class).
Can anybody please suggest how can i load each fragment to their respective tabs?
Below is my main fragment that is holding the tabs.
Thanks a lot!
public class BusFragment extends Fragment {
private TabHost mTabHost;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_bus, container, false);
mTabHost = (TabHost) rootView.findViewById(R.id.tabHost);
mTabHost.setup();
TabHost.TabSpec spec = mTabHost.newTabSpec("tag");
spec.setIndicator("Fragment1");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
spec = mTabHost.newTabSpec("tag1");
spec.setIndicator("Fragment2");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
spec = mTabHost.newTabSpec("tag2");
spec.setIndicator("Fragment3");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
return rootView;
}
}
Hello If you want to load the fragment inside the fragment android provide the Child Fragment Manager instead of ordinary fragment manager. I had the same issue I had the fragment inside that tab when click on tab want to load the different fragments. see the below steps hope will help you.
Step 1. See I have StatisticsFragment with it layout fragment_statistics.
public class StatisticsFragment extends Fragment {
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_statistics,container, false);
mTabHost = (FragmentTabHost) rootView.findViewById(R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(),R.id.tabFrameLayout);
mTabHost.addTab(mTabHost.newTabSpec("WEEK").setIndicator(buildTabLayout(EnumStatistics.WEEKLY)),WeekFragment_.class, null);
mTabHost.addTab(mTabHost.newTabSpec("ALL").setIndicator(buildTabLayout(EnumStatistics.ALL)),DetailedFragment_.class, null);
mTabHost.getTabWidget().getChildAt(0).setOnClickListener(new WeekTabClick());
mTabHost.getTabWidget().getChildAt(1).setOnClickListener(new AllTabClick());
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
private View buildTabLayout(EnumStatistics enumStatistics) {
View tab;
if (enumStatistics == EnumStatistics.WEEKLY) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_week_layout, null);
} else if (enumStatistics == EnumStatistics.MONTHLY) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_month_layout, null);
} else if (enumStatistics == EnumStatistics.YEAR) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_year_layout, null);
} else {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_detailed_layout, null);
}
return tab;
}
public class WeekTabClick implements View.OnClickListener {
#Override
public void onClick(View v) {
mTabHost.getTabWidget().focusCurrentTab(0);
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.tabFrameLayout, WeekFragment_.instantiate(getActivity(), WeekFragment_.class.getName()));
ft.addToBackStack(null);
ft.commit();
}
}
public class AllTabClick implements View.OnClickListener {
#Override
public void onClick(View v) {
mTabHost.getTabWidget().focusCurrentTab(1);
FragmentTransaction ft = getChildFragmentManager()
.beginTransaction();
ft.replace(R.id.tabFrameLayout, DetailedFragment_.instantiate(
getActivity(), DetailedFragment_.class.getName()));
ft.addToBackStack(null);
ft.commit();
}
}
}
In above buildTabLayout function intent to build the custom layout of tab widget you can put simple text or image that you want to show inside the tab widget.
Steps 2. fragment_statistics.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:relaxis="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.app.FragmentTabHost
android:id="#+id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/croutonview"
android:gravity="center" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
/>
<FrameLayout
android:id="#+id/tabFrameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
</RelativeLayout>
As you see in the above inside the layout tabFrameLayout we load the all child fragment Programmaticly.
Let me know if you have any question and doubt. thank you

Replace one fragment to another fragment in the swipable TabHost

I have an activity extending fragment activity and swipable tab view. In tab view i have used fragment and Tabs pager adapter to call fragments according to the tab position.
Now i want to replace these fragment using on click items with another fragment and on back press i want the original fragment back...
But when i am clicking on the items..it do nothing...
What should i do..pls help me ...
Thanks in advance
here is my code-
This is my Homeactivity which has tab
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
ressources = getResources();
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
// Fragments and ViewPager Initialization
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(HomeScreen.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
// Method to add a TabHost
private static void AddTab(HomeScreen activity, TabHost tabHost,
TabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(activity));
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
HomeScreen.AddTab(
this,
this.mTabHost,
this.mTabHost.newTabSpec(Button_tab).setIndicator("",
ressources.getDrawable(R.drawable.menu)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec(Image_tab).setIndicator("",ressources.getDrawable(R.drawable.jobs)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec(Text_tab).setIndicator("",ressources.getDrawable(R.drawable.people)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec("line_tab").setIndicator("",ressources.getDrawable(R.drawable.calenders)));
mTabHost.setOnTabChangedListener(this);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(Button_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Button_tab)).popFragment();
} else if (currentTabTag.equals(Image_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Image_tab)).popFragment();
} else if (currentTabTag.equals(Text_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Text_tab)).popFragment();
} else if (currentTabTag.equals(line_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(line_tab)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
My XMl for HomeActivity:
<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"
tools:context=".HomeScreen" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:src="#drawable/krma" />
<Button
android:layout_width="30dp"
android:layout_marginTop="3dp"
android:layout_height="30dp"
android:layout_marginRight="10dp"
android:layout_alignParentRight="true"
android:background="#drawable/listmenu" />
</RelativeLayout>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_weight="0"
android:background="#FF7519"
android:orientation="horizontal" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</LinearLayout>
</TabHost>
</RelativeLayout>
My TabsPagerAdapter is :
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Menu();
case 1:
return new Jobs();
case 2:
return new Applicant();
case 3:
return new Admin();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
my Job fragment is :
public class Jobs extends BaseContainerFragment implements OnItemClickListener {
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_job, container,
false);
listView = (ListView) rootView.findViewById(R.id.list);
SharedPreferences sharedpreferences = getActivity()
.getSharedPreferences(LoginScreen.MyPREFERENCES,
Context.MODE_PRIVATE);
String loggedInEmail = sharedpreferences.getString("nameKey", "");
// String loggedInEmail="aditya.pratap#krmaa.com";
RestClient client = new RestClient(
"http://122.180.4.83:8080/krmaa/krmaa/joblist/" + loggedInEmail
+ "/1234");
client.AddHeader("GData-Version", "2");
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Gson gson = new Gson();
String convertedStr = response.replace("\\\"", "\"");
String finalJson = convertedStr.substring(1, convertedStr.length() - 2);
JobDTO[] jobDTOList = gson.fromJson(finalJson, JobDTO[].class);
ItemAdapter adapter = new ItemAdapter(getActivity()
.getApplicationContext(), jobDTOList);
// Attach the adapter to a ListView
ListView listView = (ListView) rootView.findViewById(R.id.list);
listView.setAdapter(adapter);
// return list of jobDTO and iterate in view page.
return rootView;
}
public class JobDTOList {
List<JobDTO> jobDTOList;
public List<JobDTO> getJobDTOList() {
return jobDTOList;
}
public void setJobDTOList(List<JobDTO> jobDTOList) {
this.jobDTOList = jobDTOList;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here I want to switch from 1st Tab(Fragment1) to 2nd Tab(Fragment2)
// How can I switch from 1st tab to 2nd tab here???
// Below code is not worked for me.
fragment2 fr = new fragment2();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.job,fr);
transaction.commit();
}
}
My xml for Job fragment is :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/job"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="6"
android:background="#A3A385"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:text="Jobs"
android:textColor="#000000"
android:textSize="10pt" />
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#A3A385"
android:text="Filter"`enter code here`
android:onClick="frag"
android:textSize="10pt" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >`enter code here`
<ListView`enter code here`
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
</LinearLayout>

Resources