0

I currently have an Unit Converter app that I'm working in.

Here I've used multiple Blank Activities. Where each Unit's Activity can be opened using MainActivity. But now I want to make it tablet friendly.

Hence I want to use FragmentActivity now. Is it possible to convert the Blank Activities to Fragment Activities.?

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Chiranjeev Jain
  • 89
  • 3
  • 10

2 Answers2

1

All you need to do is take all View-specific logic from the Activity to a Fragment, then load the Fragment in your Activity.

For example,

public class MainActivity extends Activity {
    @InjectView(R.id.button)
    public Button button;

    @OnClick(R.id.button)
    public void onButtonClick(View view) {
         Toast.makeText(this, "Hello!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         ButterKnife.inject(this);
    }
}

This type of logic goes in

public class MainFragment extends Fragment {
    @InjectView(R.id.button)
    public Button button;

    @OnClick(R.id.button)
    public void onButtonClick(View view) {
         Toast.makeText(this, "Hello!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         View view = inflater.inflate(R.layout.fragment_main, container, false);
         ButterKnife.inject(this, view);
         return view;
    }
}

And your Activity needs to display this fragment either statically, or dynamically. If you go dynamical, you'll need the following lines in your Activity:

public class MainActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager fm = getSupportFragmentManager();
        if(savedInstanceState == null) {
            fm.beginTransaction()
                .add(R.id.container, new MainFragment())
                .commit();
        }
        fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                if(getSupportFragmentManager().getBackStackEntryCount() == 0) finish();
            }
        });

    }
}

If you go static, then you need to specify the fragments in your layout XML for the activity.

http://developer.android.com/guide/components/fragments.html#Adding

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
0

I would visit the Android website as they give a fairly good explanation on how fragments work.

You can learn how to add them to your existing application by another Android link here.

Farbod Salamat-Zadeh
  • 19,687
  • 20
  • 75
  • 125