Android : New to android, how do I initialize event handlers for elements inside a fragment

on Friday, September 12, 2014


(Disclaimer: pretty new to android) So I am trying to make a tabbed application using Android Studio, and following examples online I have been able to use the actionbar to setup 2 tabs and fragments like so:


in MainActivity.java



ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setTitle("My App Test");

Tab tabSearch = bar.newTab().setText("Search").setIcon(android.R.drawable.ic_menu_search);
Tab tabReport = bar.newTab().setText("Report").setIcon(android.R.drawable.ic_menu_report_image);

Fragment stfrag = new SearchTabFragment();
Fragment rptfrag = new ReportFragment();

tabSearch.setTabListener(new MyTabsListener(stfrag));
tabReport.setTabListener(new MyTabsListener(rptfrag));


bar.addTab(tabSearch);
bar.addTab(tabReport);


in ReportFragment/SearchTabFragment .java



public class SearchTabFragment extends Fragment {
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){

return inflater.inflate(R.layout.fragment_1,container,false);

}
}


I basically just copied the example for the ActionBar listener directly from the tutorial I found:



class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;

public MyTabsListener(Fragment fragment){
this.fragment = fragment;
};

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft){
ft.replace(R.id.wrap,fragment);
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft){

}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft){

}


}


Now my question is, how do I attach eventHandlers to the elements defined in my fragments.xml? Previously in a "Single Activity" application I played with I just put it in the main java file right after the onCreate event. Eg:



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

(TextView) tv = (TextView) findViewByid(R.id.textviewidhere);
//now I attach the handlers as I need


Thanks in advance! (edited for clarity)


0 comments:

Post a Comment