Example of using Fragments with xml layouts for better code management (by splitting ui from logic)
//mainactivity.java
public class MainActivity extends FragmentActivity implements UiListener{
private MainFragment fragment;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_main);
fragment = (MainFragment) getSupportFragmentManager().findFragmentById(R.id.main_fragment);
}
public void onButtonClicked(){
// handle button clicked
}
}
//layout/activity_main.xml
/*
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment android:name="MainFragment"
android:id="@+id/main_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
*/
//mainfragment.java
public class MainFragment extends Fragment {
public interface UiListener{
public void onButtonClicked();
}
private UiListener uiCallback;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try{
uiCallback = (UiListener) activity; // check if the interface is implemented
}catch(ClassCastException e){
e.printStackTrace();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onButtonClicked();
}
});
}
}
//layout/fragment_main.xml
/*
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp" >
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click me!" />
</RelativeLayout>
*/
3 Comments
I'll test it and let you all know ;)
Works fine. I like your example. In your case a working example did more than a dozen tutorials. Thanks for this.
The onButtonClicked(); method on the MainFragment class must be called with the UiListener interfaces object ie"uiCallback.onButtonClicked();"