Where to give functions to layout items?

19 Views Asked by At

I have created an app with swipable tabs based on this tutorial but I don't know where to define the functions of the layout items(like buttons,spinners) to the tabs. Please tell me where can I add my code so that the code works.

1

There are 1 best solutions below

4
Jim On BEST ANSWER

EDIT: Adding code to calculate values or modify the contents of views depends on when and where they are displayed. The idea behind a fragment is that it will behave and display the same in any activity. So, normally you add calculations and modifiers to the Fragment. However, if you want different behavior that is activity dependent, then you need to do those calculations in the Activity and either remove them from the Fragment objects or don't do anything there.

For example, a calculator Fragment should probably have all calculations done when the Fragment is created. But a stock market pricing calculator might need to interact with a stock picker element outside of the fragment, in which case the buttons and functions might change depending on the calculation desired. Then the Activity needs to control some calculations while the fragment controls others.


Layout items are usually added in XML files - like in step 7 of the tutorial a "TextView" is added.

However, you can also add them dynamically after you have called "setContent" like this code is adding tabs:

// Adding Tabs
for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
}

Start with XML and assign them ID's so you can reference them, like they do here:

// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

In the tutorial, the textview does not have an ID, so you can't call "findViewById" to reference it.

Hope that helps.