Finding Displayed Fragment with ViewPager or FragmentPagerAdapter - java

I have a main activity that extents ActionBarActivity and implements ActionBar.TabListener
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
View mView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
}
When a button is clicked on one of the fragments controlled by MainActivity, I have to create an intent and start another activity:
public void goToHighScore(View view) {
Intent intent = new Intent(this, DisplayScoreActivity.class);
//TextView nView = (TextView) mViewPager.getChildAt(2).findViewById(R.id.label);
TextView nView = (TextView) findViewById(R.id.label);
String highScore = nView.getText().toString();
intent.putExtra(HIGH_SCORE, highScore);
startActivity(intent);
}
However the "highScore" value is always the one equal to the fragment proceeding it?
All answers are appreciated. Thank you for bearing with me.
-Paul T.

You can get the current fragment by:
Fragment currentFragment = mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem());
Update your fragment to get the score:
Class CustomFragment extends Fragment{
private TextView nView;
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
nView = view.findViewById(R.id.label);
}
public String getScore(){
return nView.getText().toString();
}
}
And function will look like:
public void goToHighScore(View view) {
Intent intent = new Intent(this, DisplayScoreActivity.class);
Fragment currentFragment = mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem());
String highScore = currentFragment.getScore();
intent.putExtra(HIGH_SCORE, highScore);
startActivity(intent);
}
However, I will suggest you to handle the onClick event in your fragment to provide better encapsulation. Update your fragment as follows:
Class CustomFragment extends Fragment{
private TextView nView;
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
nView = view.findViewById(R.id.label);
Button button = (Button)findViewByid(R.id.button)
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String highScore = nView.getText().toString()
intent.putExtra(HIGH_SCORE, highScore);
startActivity(intent);
}
});
}
}
By doing this your Fragment can be attached to different activity without functionality broke down.

Related

How can i show toolbar back button in fragments in android?

I am working on an android application where I have three fragments I want to show the back button on the toolbar of the fragments to go back to the previous fragments now how can I achieve that?? I am new to android please guide me.
public class SecondFragment extends Fragment {
Button button2;
private PageViewModel viewModel;
EditText editTextName, editTextEmail, editTextDesc;
public SecondFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#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);
button2 = view.findViewById(R.id.next2);
editTextName = view.findViewById(R.id.edittextName);
editTextEmail = view.findViewById(R.id.edditextEmail);
editTextDesc = view.findViewById(R.id.edittexDesc);
viewModel = new ViewModelProvider(requireActivity()).get(PageViewModel.class);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (editTextName.getText().toString().isEmpty() || editTextEmail.getText().toString().isEmpty() || editTextDesc.getText().toString().isEmpty())
{
editTextName.setError("Enter name");
editTextEmail.setError("Enter Email");
editTextDesc.setError("Enter Description");
}else {
// viewModel.setName(editTextName.getText().toString());
enterName(editTextName.getText().toString());
enterEmail(editTextEmail.getText().toString());
enterDesc(editTextDesc.getText().toString());
// viewModel.setEmail(editTextEmail.getText().toString());
// viewModel.setDescription(editTextDesc.getText().toString());
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment NAME = new LastFragment();
fragmentTransaction.replace(R.id.container, NAME);
fragmentTransaction.commit();
}
}
});
return view;
}
this is the code of my fragment borther i have three fragments like this i need to add the back button on the toolbar of there three fragemtns
You can add a toolbar to your activity, which is the container for these fragments.
Then in your fragments you can do something like this:
private void setupToolbar() {
YourActivity yourActivity = (YourActivity) getActivity()
if(yourActivity != null) {
yourActivity.toolbar.setSkipVisibility(View.GONE) // Or View.VISIBLE
yourActivity.toolbar.setText() // Set some text
yourActivity.toolbar.setOnBackButtonClickListener{ yourActivity.onBackPressed() }
}
}
Follow the steps down below.
fragmentTransaction.replace(R.id.container, NAME);
fragmentTransaction.addToBackStack(null); //Add this line
fragmentTransaction.commit();
This will solve your issue. Thank you.

Android - Open 3rd Tab from Intent fired from Dialog in Fragment

I have ALr.java class and FragHandler. FragHandler has Tablayout and viewpager. ALR and FragHandler code is writtern below. I want to open Settings tab which is third tab in FragHandler from click on ALR i.e. rl.setonclicklisterner by calling activatealert method.
MyFragHandler Class
public class FragHandler extends AppCompatActivity
TabLayout tabLayout;
Toolbar customtoolbar;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alstabopener);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("1"));
tabLayout.addTab(tabLayout.newTab().setText("2"));
tabLayout.addTab(tabLayout.newTab().setText("Settings"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final AlsViewChanger adapter = new AlsViewChanger(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
and my ALR.java from where I m trying to open tab 3.
public class ALR extends Fragment {
TextView rl,
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) throws NullPointerException {
View view = inflater.inflate(R.layout.ar, container, false);
rl = (TextView) view.findViewById(R.id.reto);
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activatealert();
});
public void activatealert() {
MaterialDialog activateald = new MaterialDialog.Builder(getActivity())
.content("In order to use these services, please click settings and set appropriate options to activate Where R U feature.")
.title("Activate Where R U")
.positiveColor(Color.BLUE)
.negativeColor(Color.RED)
.positiveText("Settings")
.negativeText("Cancel")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
Intent intent = new Intent(getActivity(),FragHandler.class);
intent.putExtra("Settings",2);
startActivity(intent);
}
})
.show();
}
}
it opens tabbed activitiy but First Tab not third as required. Pls guide.
Edit Based on your code:
remove the OnTabSelectedListener, you don't need it.
just add
tabLayout.setupWithViewPager(viewPager);
Here's the full code:
public class FragHandler extends AppCompatActivity
TabLayout tabLayout;
Toolbar customtoolbar;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alstabopener);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("1"));
tabLayout.addTab(tabLayout.newTab().setText("2"));
tabLayout.addTab(tabLayout.newTab().setText("Settings"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final AlsViewChanger adapter = new AlsViewChanger(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
int tabToSelect = getIntent().getIntExtra("Settings”, 0);
viewPager.setCurrentItem(tabToSelect);
}
}
Please check the
int tabToSelect = getIntent().getIntExtra("Settings”, 0);
I just assumed if you wanted to do so. Change it according if you don't need it.
It's hard to answer without much details, but here are my few suggestion based on assumptions:
1) You want to start an activity FragHandler which has multiple tabs. TabLayout is associated with ViewPager. so in that case, after you set adapter to ViewPager, call viewPager.setCurrentItem(2). If you have only tabs, then you can try tabLayout.getTabAt(2).select(). This should trigger your OnTabSelectedListener where you might already have code for replacing fragment.
2) The fragment which is having dialog is inside the same TabLayout where 3rd tab you are asking for is. In this case put the following code in onClick of settings button:
// If ViewPager, then make it public in YourActivity
((YourActivity)getActivity()).viewPager.setCurrentItem(2);
// If TabLayout without ViewPager, then also make it public
((YourActivity)getActivity()).tabLayout.getTabAt(2).select();
And post as much details as possible so that you can get correct answer

Unable to set text in fragment

I am trying to call a function from my mainActivity to change a TextView in one of my fragments. I have read a couple posts on the best way of doing it but for some reason, none of them seem to work for me. I know the function is working because once a press the button the toast comes up but for some reason the text won't change. I was wondering what the issue could be, or if I am just missing an additional step.
here is the method being called in my mainActivity
public class MainActivity extends AppCompatActivity implements Tab1Fragment.OnCalcClickListener{
private static final String TAG = "MainActivity";
private SectionsPageAdapter mSectionsPageAdpater;
private ViewPager mViewPager;
Tab1Fragment tab1Fragment = new Tab1Fragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Starting");
//initializing FragmentManager so the fragments can communicate
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, tab1Fragment);
fragmentTransaction.commit();
//declare sections page adapter
mSectionsPageAdpater = new SectionsPageAdapter(getSupportFragmentManager());
//Set up the view pager with the sections adapter
mViewPager = (ViewPager) findViewById(R.id.container);
setUpViewPager(mViewPager);
//create a tab layout object and set it's id to tabs (mainActivity.xml)
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
//
}
// create a sections page view adapter
private void setUpViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment(), "Day");
adapter.addFragment(new Tab2Fragment(), "Info");
adapter.addFragment(new Tab3Fragment(), "Week");
viewPager.setAdapter(adapter);
}
//initialise calculator object
Calculator mainCalculator = new Calculator();
#Override
public void calculateClick(int to_calculate) {
switch (to_calculate){
case 1:
Toast.makeText(getBaseContext(),"working", Toast.LENGTH_SHORT).show();
mainCalculator.freqDay = mainCalculator.freqDay + 1;
mainCalculator.freqWeek = mainCalculator.freqWeek + 1;
mainCalculator.getTotalDay();
tab1Fragment.updateInfo();
break;
}
}
Here is the code for my fragment
public class Tab1Fragment extends Fragment implements
View.OnClickListener{
private static final String TAG = "Tab1Fragment";
//Establishing the buttons & Methods
Button btn1;
Button btn2;
TextView dayView;
OnCalcClickListener onCalcClickListener;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_fragment, container, false);
//Connecting the buttons to the xml
btn1 = (Button) view.findViewById(R.id.btn_1);
btn1.setOnClickListener(this);
btn2 = (Button) view.findViewById(R.id.btn_2);
btn2.setOnClickListener(this);
dayView = (TextView) view.findViewById(R.id.total_Sales_Day);
return view;
}
//Onclick listener for buttons
public void setOnClickListener(View.OnClickListener listener) {
btn1.setOnClickListener(listener);
btn2.setOnClickListener(listener);
}
//method that will bring data back from activity and set the text
public void updateInfo(){
Toast.makeText(getContext(),"65", Toast.LENGTH_SHORT).show();
dayView.setText("test");
}
To make calls to methods from your fragment in the activity class you need something like this:
public static class MainActivity extends Activity
implements HeadlinesFragment.OnHeadlineSelectedListener{
...
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Do something here to display that article
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// Otherwise, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
Here the activity is calling the updateArticleView method from the fragment, instead of your updateInfo method, but you will get the idea.
Also pay attention to the one-pane scenario, where you need to swap the content and push the arguments using a Bundle object.
See Deliver a Message to a Fragment for more details.
When you add the fragment set a tag to it like this:
MyFragment frag = new MyFragment();
frag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, frag, "TAG").commit();
While updating the textview get the instance of fragment using findFragmentByTag()
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag("TAG");
fragment.updateInfo();

Add items to ListView in a fragment in one Activity by clicking a button in another activity

first off I apologize if a similar question has already been asked and answered, but I have looked through tons of posts without any luck. Second, I am an absolute beginner (been coding for 6 weeks), so if I'm missing some concepts or if there is a better way to do things, feel free to enlighten me.
Now, here is my question:
On my MainActivity, I have an EventsFragment which has a ListView. There is also a FloatingActionBar on the MainActivity, which when clicked loads another Activity called CreateEventActivity. The CreateEventActivity has an EditText field and a Create Button. What I wanna do is when the User enters some text in the EditText field and clicks the create Button, it should take the string from the EditText field and create an item on the ListView with String as it's name. Also, as soon as the create button is clicked, it should go back to the EventsFragment in the MainActivity.
I used startActivityForResults(), as suggested and it seems that I am able to pass an ArrayList as an intent from CreateEventActivity back to MainActivity, and that is as far as I'm able to get. I think the way I'm sending the list to the EventsFragment is wrong, as the listView is not updating.
MainActivity -
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), MainActivity.this);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
//Iterate over all TabLayouts to set the custom View
for (int i = 0; i < tabLayout.getTabCount(); i++){
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(mSectionsPagerAdapter.getTabView(i));
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadCreateEventActivity();
// Snackbar.make(view, "Here the create a New Event Screen will be displayed", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
}
});
}
private void loadCreateEventActivity(){
Intent intent = new Intent(MainActivity.this, CreateEventActivity.class);
startActivityForResult(intent, 2);
}
public ArrayList<String>list = new ArrayList<>();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2){
if (resultCode == RESULT_OK) {
list = data.getStringArrayListExtra("LIST_ITEMS");
}
}
}
public ArrayList<String> getList() {
return list;
}
CreatEventsActivity -
public class CreateEventActivity extends AppCompatActivity {
EditText createEventName;
Button createButton;
ArrayList<String> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
createEventName = (EditText) findViewById(R.id.createEventName);
createButton = (Button) findViewById(R.id.createButton);
listItems = new ArrayList<String>();
listItems.add("First Item - added on Activity Create");
createButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listItems.add(createEventName.getText().toString());
Intent intent = new Intent();
intent.putStringArrayListExtra("LIST_ITEMS", listItems);
setResult(RESULT_OK, intent);
createEventName.setText("");
finish();
}
});
}
}
EventsFragment -
public class EventsFragment extends Fragment {
public EventsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_events, container, false);
MainActivity mainActivity = (MainActivity) getActivity();
ArrayList<String>list = mainActivity.getList();
ListView listView = (ListView)view.findViewById(R.id.list_view);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return view;
}
}
Thanks for any help in advance :)
Solution 1 :
You need to have one data set, that is common to both activities.
Every time you click, you add add an item to that data set.
The list view is populated using that very same data set.
Since they are both in different activities, you need to persist that data set.
You can persist it locally, by storing it using a table(database) or as a json string, in [shared preference][1].
Another short cut to persist the data set is to have your data set as a property in your Application class, so you can add and access the dataSet from any activity in the app, as the application class is alive for the entire lifecycle of the app.
I DON'T RECOMMEND THIS. This is easy and it works, but it is not good practice and leads to terrible code quality, but if you just want a quick way to do it, you can do it.
Solution 2 : In your main activity, start the second activity using startActivityForResult(). What this will let you do is let second activity talk back to the first one. So when it talks back, you can know in the first one, how many items were added in the second one and update your first activity's listView accordingly.

Access method from Dialog to MainActivity

I have a main Activity in which I created a ViewPager that instantiate 3 other Fragments. One of these is a GridView which makes a popup appear when the user click on one item. Then, in this popup, I have a simple button.
What I want to do is: when the user click on this button, I would like to access a method in my main Activity (that should change the current item of my ViewPager) and then dismiss the popup.
I tried everything I could, but I cannot achieve this... I can set up the click event on my popup and dismiss it easily, but I didn't find out how I can access a method (or even a variable) from my popup to my main Activity.
I will put my most relevant code in here so you can understand the structure of my classes (hopefully...).
My main Activity:
public class MainActivity extends FirstActivity{
private ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Set an Adapter on the ViewPager
mViewPager.setAdapter(new MainActivity_Adapter(getSupportFragmentManager()));
public void onSaveInstanceState(Bundle savedInstanceState)
{
menuBar.onSaveInstanceState(savedInstanceState);
}}
My ViewPager activity:
public class MainActivity_Adapter extends FragmentPagerAdapter{
public MainActivity_Adapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
// Set the color background for each page
switch (position)
{
case 0:
return MainActivity_Inventory.newInstance();
case 1:
return MainActivity_Map.newInstance();
default:
return MainActivity_AR.newInstance();
}
}
// The number of Splash Screens to display
#Override
public int getCount()
{
return 3;
}}
My "Inventory" Fragment
public class MainActivity_Inventory extends Fragment implements View.OnClickListener{
public static MainActivity_Inventory newInstance()
{
MainActivity_Inventory frag = new MainActivity_Inventory();
Bundle b = new Bundle();
frag.setArguments(b);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Select the layout
int layout;
layout = R.layout.activity_inventory_01;
// Inflate the layout resource file
View view = getActivity().getLayoutInflater().inflate(layout, container, false);
// Set the grid view
GridView gridview = (GridView) view.findViewById(R.id.inventory_gridView);
gridview.setAdapter(new InventoryImageAdapter(super.getActivity()));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v, int position, long id)
{
// Create a popup to show item details
createPopup();
}
});
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
}
public void createPopup()
{
DialogFragment newFragment = new PopupActivity_Inventory();
newFragment.show(getFragmentManager(), "itemDetails");
}
#Override
public void onClick(View v)
{
}}
And my popup dialog fragment:
public class PopupActivity_Inventory extends DialogFragment{
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState)
{
// Build the alert dialog
final Dialog dialog = new Dialog(this.getActivity());
// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();
// Set up the dialog box
dialog.setContentView(inflater.inflate(R.layout.activity_inventory_popup_01, null));
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().setGravity(Gravity.TOP);
//dialog.getWindow().getAttributes().y = 100;
(dialog.findViewById(R.id.brick_button_01)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
// When button is clicked, ACCESS MAIN ACTIVITY!
dialog.dismiss();
}
});
return dialog;
}}
I really hope you can help me with this... I really need to get it working. Thank you very much!
If you need further details or explanation, please just tell me.
The best thing to do is use EventBus library. I have a demo app in which you can add items to RecyclerView from anywhere within the app using EventBus. You can use it as a reference to simply do something else instead of current task. Here is the link to the repo:
https://github.com/code-crusher/android-demos/tree/master/EventBusDemo
And if you want to understand how it works you can refer to my article, it explains how to make communications like this easy:
https://medium.com/#code_crusher/eventbus-for-android
Hope it helps. Happy coding :)
Read this https://developer.android.com/training/basics/fragments/communicating.html
Look for "To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity...."
Another way to achieve it is using an EventBus and post events by Fragments to be caught by Activities.

Categories