I have two tabs which contain two different fragments. Tab1 for fragment1 and tab2 for fragment2. From fragment1, I want to pass a string value in fragment2's TextView by clicking on a Button.
However, the UI of fragment2 is not being updated. Sample code has given below.
In MainActivity :
private Fragment1 fragment1;
private Fragment2 fragment2;
private TabLayout tabLayout;
protected void onCreate(Bundle savedInstanceState) {
fragment1 = new Fragment1();
fragment2 = new Fragment2();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment1).commit();
tabLayout = (TabLayout) findViewById(R.id.tab);
tabLayout.getTabAt(0).select();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment1).commit();
} else if (tab.getPosition() == 1) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
}
public void showFragment2(final String data) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
tabLayout.getTabAt(1).select();
if (!TextUtils.isEmpty(data)) {
if (fragment2 != null) {
fragment2.setData(data);
}
}
}
In Fragment1 :
private Button button;
protected void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
button = (Button) view.findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).showFragment2("Updated Data");
}
});
}
In Fragment2 :
private TextView tv;
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv = (TextView) view.findViewById(R.id.tv);
}
public void setData(String data){
tv.setText(data);
}
Important Update:
If I update the UI in Handler. Then it works. But, seems it's not the proper way.
handler.postDelayed(new Runnable() {
#Override
public void run() {
tabLayout.getTabAt(1).select();
if(!TextUtils.isEmpty(data)){
if(fragment2 != null){
fragment2.setData(data);
}
}
}
},500);
Use .executePendingTransactions() which would work synchronously along with .commit() which works Asynchronously.
After a FragmentTransaction is committed with
FragmentTransaction.commit(), it is scheduled to be executed
asynchronously on the process's main thread. If you want to
immediately executing any such pending operations, you can call this
function (only from the main thread) to do so. Note that all callbacks
and other related behavior will be done from within this call, so be
careful about where this is called from.
DO:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
getSupportFragmentManager().executePendingTransactions();
tabLayout.getTabAt(1).select();
if(!TextUtils.isEmpty(data)){
if(fragment2 != null){
fragment2.setData(data);
}
}
Hey hi i am not sure but try this:
public void showFragment2(final String data) {
if (!TextUtils.isEmpty(data)) {
if (fragment2 != null) {
// fragment2.setData(data);
Bundle arguments = new Bundle();
arguments.putString( "string_key" , data);
fragment2.setArguments(arguments);
}
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
tabLayout.getTabAt(1).select();
}
and In Fragment2 :
private TextView tv;
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle arguments = getArguments();
String desired_string = arguments.getString("string_key");
tv = (TextView) view.findViewById(R.id.tv);
setData(desired_string);
}
public void setData(String data){
tv.setText(data);
}
set the data in activity method from fragment 1 and while loading fragment get the data from activity and set it in fragment 2
mainActivity(){
string fragment1Data;
public void setFragment1Data(string data){
fragment1Data = data;
}
public string getFragment1Data(){
return fragment1Data
}
}
in Fragment 1
private Button button;
protected void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
button = (Button) view.findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).showFragment2("Updated Data");
((MainActivity)getActivity()).setFragment1Data("data");
}
});
}
in Fragment 2
private TextView tv;
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv = (TextView) view.findViewById(R.id.tv);
tv.setText(((MainActivity)getActivity()).getFragment1Data());
}
Related
I wrote this code for login and for chatting;
login is an activity where is chatting is a fragment; here is my activity :
public class Consultant extends AppCompatActivity {
private FirebaseAuth auth;
private Button loginbtn;
private EditText email;
private EditText pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consultant);
auth = FirebaseAuth.getInstance();
loginbtn = (Button) findViewById(R.id.loginbtn);
email = (EditText) findViewById(R.id.email);
pass = (EditText) findViewById(R.id.pass);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkEmailandpassword();
}
});
}
public boolean checkEmailandpassword() {
if (validate()) {
String CEmail = email.getText().toString().trim();
String CPass = pass.getText().toString().trim();
auth.signInWithEmailAndPassword(CEmail, CPass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(Consultant.this, "welcome", Toast.LENGTH_LONG).show();
Intent i = new Intent(Consultant.this,Consultant_Home_Chatting.class);
startActivity(i);
} else {
Toast.makeText(Consultant.this, "wrong ", Toast.LENGTH_LONG).show();
}
}
});
}
return false;
}
private boolean validate() {
boolean result = false;
String CPass = pass.getText().toString();
String CEmail = email.getText().toString();
if (CPass.isEmpty() || CEmail.isEmpty()) {
Toast.makeText(Consultant.this, "all fields required", Toast.LENGTH_LONG).show();
} else {
result = true;
}
return result;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_nav, menu);
return true;
}
}
and here my fragment :
public class Consultant_Home_Chatting extends Fragment {
private ViewPager mViewP ;
private FirebaseAuth mAuth ;
private TabLayout mTab ;
private TabsPagerAdapter mAdapter ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_consultant__home__chatting, container, false);
}
public Consultant_Home_Chatting() {
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
mAuth = FirebaseAuth.getInstance();
mViewP = (ViewPager) getView().findViewById(R.id.main_tabs_pager);
mAdapter = new TabsPagerAdapter(getFragmentManager());
mViewP.setAdapter(mAdapter);
mTab = (TabLayout) getView().findViewById(R.id.main_tabs);
mTab.setupWithViewPager(mViewP);
}
I tried to add a new class holding these liens then make a constructor in my fragment and onCreatOptions method in my activity but it does not work!
I think the solution is to use the Bundle but I don't know how to use it or can I use it and what can I send inside put extra, can you please help?
if (savedInstanceState == null){
getFragmentManager().beginTransaction()
.add(android.R.id.content, new Consultant_Home_Chatting ()).commit();}
to use bundle simple create the instance of your fragment and then create bundle add all data you want and add this bundle to the fragment.
Here is example:
In activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TestFragment testFragment = new TestFragment();
Bundle bundle = new Bundle();
bundle.putString("name", "John");
bundle.putInt("age", 24);
testFragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, testFragment).commit();
}
In your fragment:
public class TestFragment extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if(bundle != null){
String name = bundle.getString("name");
int age =`enter code here` bundle.getInt("age");
}
}
}
I am using the following components in my application
Activity
Fragment
WebView
Goal - I don't want to reload the webview on orientation change.
Issue - Currently I see the following error on orientation change "Webpage was not available. The webpage at https://fakeurls.org could not be loaded because net::ERR_CACHE_MISS"
Steps to Reproduce
Application was opened in device portrait mode.
Content of given URL was loaded in webview successfully
Device was turned to landscape mode
Webview shows error
Code - Android application makes a post request in a webview to url https://fakeurls.org. Below is the code for MyActivity and MyFragment class
MyFragment.java
public class MyFragment extends Fragment {
private ProgressBar mProgressBar;
private WebView mWebView;
private String mUrl = null;
private String mPostData = null;
public MyFragment() {
// Required empty public constructor
}
public static MyFragment newInstance(#android.support.annotation.NonNull String url, String postData) {
MyFragment MyFragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("URL", url);
bundle.putString("POSTDATA", postData);
MyFragment.setArguments(bundle);
return MyFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_fragment, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
instantiateWebView(view);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
} else {
Bundle args = getArguments();
if (args == null) {
return;
}
mUrl = args.getString("URL");
mPostData = args.getString("POSTDATA");
mWebView.postUrl("https://fakeurls.org/", EncodingUtils.getBytes(mPostData, "BASE64"));
}
}
#Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
if (mWebView != null) {
mWebView.saveState(outState);
}
}
#Override
public void onDestroy() {
super.onDestroy();
mWebView.destroy();
}
private void instantiateWebView(View view) {
mWebView = (WebView) view.findViewById(R.id.webView);
mWebView.setWebViewClient(new WebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
}
}
MyActivity.java
public class MyActivity extends AppCompatActivity {
private MyFragment mMyFragment;
#NonNull
public static Intent createIntent(Context context, String url, String postData) {
return new Intent(context, MyActivity.class).putExtra("URL", url)
.putExtra("POSTDATA", postData);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_link_viewer);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mMyFragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_frame);
if (mMyFragment == null) {
final String url = getIntent().getStringExtra("URL");
final String postData = getIntent().getStringExtra("POSTDATA");
mMyFragment = MyFragment.newInstance(url, postData);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_frame, mMyFragment)
.commitNow();
}
}
#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);
}
#Override
public void finish() {
mMyFragment.cancelTasks();
super.finish();
}
}
Please let me know how to resolve the issue and not reload the webview but retain display on orientation change. Any help is appreciated.
I have three fragments in the same activity, let says FragmentA, FragmentB and FragmentC
Let´s say that FragmentA sends an int to FragmentB so in the FragmentA I have:
//FRAGMENT_A
#Override
public void onDestroy() {
super.onDestroy();
EventBus.getBus().register(this);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
EventBus.getBus().register(this);
}
private void registerEventBus(int i) {
EventBus.getBus().post(i);
}
FragmentB received the int so:
//FRAGMENT_B
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getBus().register(this);
}
#Override
public void onDestroyView() {
super.onDestroyView();
EventBus.getBus().unregister(this);
}
#Subscribe
public void getBusData(int data) {
//whatever
}
But now I have to send a double from FagmentB to FragmentC, I have created a new Bus class so now in the FragmentB, I have
//Fragment_B
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getBus().register(this);
EventBus2.getBus.register(this)
}
#Override
public void onDestroyView() {
super.onDestroyView();
EventBus.getBus().unregister(this);
EventBus2.getBus..unregister(this)
}
#Subscribe
public void getBusData(int data) {
//whatever
}
private void createEventBus2(double number){
EventBus2.post(number);
}
And finally the FragmentC
//FragmentC
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus2.getBus().register(this);
}
#Override
public void onDestroyView() {
super.onDestroyView();
EventBus2.getBus().unregister(this);
}
#Subscribe
public void getBus2Data(double data) {
//whatever
}
From FragmentA to FragmentB works perfectly but in the FragmentC I have never get the double data value.
What am I doing wrong?
What i am trying to do:: I am trying to save the data entered into edittext and spinner onorientation change
What is happening::: I am not able to save the data, how can i resolve this
MainActivity.java
public class MainActivity extends FragmentActivity {
Fragment_A frgObj;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
Log.d("MAIN-ACTIVITY", "onCreate");
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
Log.d("MAIN-ACTIVITY", "onStart");
frgObj=Fragment_A.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.container, frgObj).addToBackStack(null).commit();
}
public void onSaveInstanceState(Bundle outState){
getSupportFragmentManager().putFragment(outState,"myfragment",frgObj);
}
public void onRetoreInstanceState(Bundle inState){
frgObj = (Fragment_A) getSupportFragmentManager().getFragment(inState,"myfragment");
}
}
Fragment_A.java
public class Fragment_A extends Fragment{
Button btn;
Spinner spinner;
EditText editText;
SeekBar seekBar;
public static Fragment_A newInstance() {
Log.d("FRAGMENT-A", "newInstance");
Fragment_A fragment = new Fragment_A();
return fragment;
}
#Override
public void onAttach(Activity activity) {
Log.d("FRAGMENT-A", "onAttach");
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d("FRAGMENT-A", "onCreate");
super.onCreate(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d("FRAGMENT-A", "onSaveInstanceState");
super.onSaveInstanceState(outState);
//City Spinner state
outState.putString("editText", editText.getText().toString());
outState.putInt("yourSpinner", spinner.getSelectedItemPosition());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("FRAGMENT-A", "onCreateView");
View view=inflater.inflate(R.layout.fragment_a, container, false);
btn=(Button) view.findViewById(R.id.buttonId1);
spinner=(Spinner) view.findViewById(R.id.spinnerId1);
editText=(EditText) view.findViewById(R.id.editTextId1);
seekBar=(SeekBar) view.findViewById(R.id.seekBarId1);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d("FRAGMENT-A", "onActivityCreated");
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
//City Spinner state
editText.setText(savedInstanceState.getString("editText"));
spinner.setSelection(savedInstanceState.getInt("yourSpinner", 0));
}
}
#Override
public void onStart() {
Log.d("FRAGMENT-A", "onStart");
super.onStart();
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("FRAGMENT-A", "button Clicked");
Fragment_B frgObj=Fragment_B.newInstance();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, frgObj,"Fragment_B").addToBackStack(null).commit();
}
});
}
}
I don't think you need to change anything in your activity other than call super.onSaveInstanceState(Bundle). Saving the data onSaveInstanceState in the fragment should be enough. I would put the restoring logic in onCreateView instead of onActivityCreated. onCreateView is guaranteed to be called whenever the fragment is recreated however this is not the case with onActivityCreated.
An other thing you can try is not going any of this and using setRetainInstance(true) which should retain your instance variables through orientation change.
I did a quick search in here and didn't find any answers for my qustion, if its already answered please point me to that question ..
I have an ActionBar Tabs with swipe views implemented according to this android training. My activity have 3 tabs
Weather Comment Dashboard
and these fragments
WeatherFragment CommentsFragment LoginFragment DasboardFragment RegisterFragment
As the activity is started,
Weather Tab displays WeatherFragment ,
Comments Tab displays CommentsFragment and
Dashboard Tab displays LoginFragment
If Login is successful in LoginFragment, DasboardFragment should replace the LoginFragment inside the Dashboard Tab. So if user swipes to other tabs and come back to Dashboard Tab DasboardFragment should be visible.
I'm new to android development, so any code snippets or tutorial would be greatly appreciated
Code i've so far MainActivity class
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_network_weather);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(
getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
//actionBar.setDisplayShowTitleEnabled(false);
//actionBar.setDisplayShowHomeEnabled(false);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new WeatherInfoFragment();
case 1:
return new PostsFragment();
default: //TODO method to find which fragment to display ?
return new LoginFragment();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Weather";
} else if (position == 1){
return "Comments";
}
else{
return "Dashboard";
}
}
}
#Override
public void onTabReselected(ActionBar.Tab tab,
android.app.FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
}
}
LoginFragment
public class LoginFragment extends Fragment implements AsyncResponse {
Button loginButton;
TextView loginError, login_url;
JSONfunctions task;
JSONObject jsonObject;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.login, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
loginButton = (Button) getView().findViewById(R.id.button_login);
loginError = (TextView) getView().findViewById(R.id.login_error);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin(finalLoginUrl);
// attemptPost(postURL);
}
});
}
private void attemptLogin(String url) {
try {
task = new JSONfunctions(getActivity());
task.listener = this;
task.execute(new String[] { url });
} catch (Exception ex) {
Log.e("attempt login", ex.getMessage());
}
}
}
#Override
public void processFinish(String result) {
try {
jsonObject = new JSONObject(result);
int success = Integer.parseInt(jsonObject.getString("Success"));
if (success == 0) {
// Replace LoginFragment and launch DashboardFragment ?
} else {
loginError.setText(jsonObject.getString("ErrorMessage"));
}
} catch (JSONException e) {
Log.e("JSON parsing from login result", e.getMessage());
}
}
}
I'm not sure this is the best way to handle this but you could define a static boolean inside your MainActivity like so:
public static boolean loggedIn = false;
(e.g. below ViewPager mViewPager;)
And then, in your method processFinish(...) inside the LoginFragment when success is 0 just set MainActivity.loggedIn = true;
This way you can simply put in an if-statement inside your default-case in getItem-method to check whether the user is logged in (if so call the Dashboard-Fragment) or not (display Login-Fragment).
Hope this works for you!
Edit: LoginFragment
public class LoginFragment extends Fragment implements AsyncResponse {
Button loginButton;
TextView loginError, login_url;
JSONfunctions task;
JSONObject jsonObject;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.login, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
loginButton = (Button) getView().findViewById(R.id.button_login);
loginError = (TextView) getView().findViewById(R.id.login_error);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin(finalLoginUrl);
// attemptPost(postURL);
}
});
}
private void attemptLogin(String url) {
try {
task = new JSONfunctions(getActivity());
task.listener = this;
task.execute(new String[] { url });
} catch (Exception ex) {
Log.e("attempt login", ex.getMessage());
}
}
#Override
public void processFinish(String result) {
try {
jsonObject = new JSONObject(result);
int success = Integer.parseInt(jsonObject.getString("Success"));
if (success == 0) {
MainActivity.loggedIn = true;
} else {
loginError.setText(jsonObject.getString("ErrorMessage"));
}
} catch (JSONException e) {
Log.e("JSON parsing from login result", e.getMessage());
}
}
}
Was my own fault for not reading the answer here thoroughly. Implemented the code from that answer and got the functionality working :)