Converting Activity into Fragment

converting activity into fragment

  1. Fragment has a method called onCreateView(LayoutInflater, ViewGroup, Bundle). Override it, inflate using the layout and return the view.
  2. Since create method expects a Context, pass it using getActivity()
  3. findViewById(int) can be called as getView().findViewById(R.id.button3)

Here is a sample code:

public class Rajathmusic extends Fragment {

private static final String TAG = "MyActivity";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.v(TAG, "Initializing sounds...");

final MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.rajath);

View v = getView();

Button play_button = (Button) v.findViewById(R.id.button3);

play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Playing sound...");
mp.start();
}
});
Log.v(TAG, "Sounds initialized.");
}

}

Read more about Fragment lifecycle here to know why I've put the code in onActivityCreated and not onCreate

How to convert an activity to fragment in Android studio

I would start by understanding their lifecycles (activity and fragment). We can then have a good idea of where to move your code from onCreate() in activity to onViewCreated() in Fragment. Also notice that activity extends AppCompatActivity while Fragment extends Fragment class. With those two observations we can now proceed as below. Note the renaming of the layout and class due to the change from activity to class.

class SplashFragment extends Fragment {
private FirebaseAuth auth;
private FirebaseUser user;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

auth = FirebaseAuth.getInstance ();
user = auth.getCurrentUser ();

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

@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
new Handler().postDelayed (new Runnable () {
@Override
public void run() {
//Do your logic here.
}
}, 1500);
}

}

References:
Fragment lifecycle: https://developer.android.com/guide/fragments/lifecycle
Fragment implementation: https://developer.android.com/guide/fragments/create

How to convert activity into fragment?

You can change your activity into fragment like this :

public class FragmentClass extends Fragment  
{
private View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = (View) inflater.inflate(R.layout.layout_history, container,false);

//Do all things which you want to implement //enter code here
return view;
}
}

You need to extends Fragment and override its onCreateView(LayoutInflater, ViewGroup, Bundle) method.
Inflate it using layout and return view like above.

You can also create member of this fragment using its view and pass context using:

getActivity();

If you want to use findViewById(int) then you would use it like :

getView().findViewById(int);

If you want to know more about this then go to: http://developer.android.com/guide/components/fragments.html
& http://developer.android.com/reference/android/app/Fragment.html#Lifecycle

You can create custom fragment like below. After all of this you can use your methods using getActivity() from fragment class.

And about error of your methods then you have to use context of current fragment class.

Example if you want to use TextView then:

TextView tv = (TextView) context.findViewById(R.id.textView);

I am showing example how to make fragment using BaseActivity :

public class MainActivity extends BaseActivity 
{
private FragmentClass fragmentClass;
private ViewPager mViewPager;

private SlidingTabLayout mSlidingTabLayout;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Do all stub
populateView();
}

private void populateView()
{
mViewPager = (ViewPager) findViewById(R.id.pager1);
mViewPager.setOffscreenPageLimit(2);
mViewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setDividerColors(color);
mSlidingTabLayout.setCustomTabView(R.layout._custom_tab, 0);
mSlidingTabLayout.setViewPager(mViewPager);
}

class ViewPagerAdapter extends FragmentPagerAdapter
{
public ViewPagerAdapter(FragmentManager fm)
{
super(fm);
// TODO Auto-generated constructor stub
}

@Override
public Fragment getItem(int pos)
{
if(pos==0)
{
fragmentClass = new FragmentClass();
return fragmentClass;
}
return null;
}

@Override
public int getCount()
{
// TODO Auto-generated method stub
return 1;
}
}
}

Add Two classes from developer.android :

  1. Sliding Tab Layout
  2. Sliding TabStrip

http://developer.android.com/samples/SlidingTabsBasic/src/com.example.android.common/view/SlidingTabLayout.html

Convert Activity into a Fragment

setContentView()

There is no method like this in Fragments. Instead, you override onCreateView() and return some view from it. You can use the passed-in LayoutInflater to inflate the layout id you'd normally pass to setContentView(), and then return that.

findViewById()

Fragments do not have a findViewById() method. However, any time after onCreateView() returns, you can instead use getView().findViewById(). Inside onCreateView(), if you named your inflated view root you could call root.findViewById(). Prior to onCreateView(), there's no way to look up any views (since they haven't been inflated yet).

getMenuInflater()

Fragments use a different signature for onCreateOptionsMenu(). It looks like this:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// ...
}

You can use the passed-in MenuInflater instead of calling getMenuInflater().


Put that all together, and this is what you'd have:

public class LocationsFragment extends Fragment {

RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerView.Adapter adapter;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.activity_card_demo, container, false);

recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);

layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);

adapter = new RecyclerAdapter();
recyclerView.setAdapter(adapter);

return root;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_card_demo, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

how do i convert this activity into fragment and fragment to navigation

Create you own fragment class for home, dashboard and notification.

public class QuestionPaper extends Fragment {
private TextView mTextMessage;

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
HomeFragment homeFragment = HomeFragment.newInstance();
createFragment(homeFragment);
return true;
case R.id.navigation_dashboard:
DashBoardFragment dashBoardFragment = DashBoardFragment.newInstance();
createFragment(dashBoardFragment);
return true;
case R.id.navigation_notifications:
NotiFragment notiFragment = NotiFragment.newInstance();
createFragment(notiFragment);
return true;
}
return false;
}
};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_question_paper, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mTextMessage = (TextView) view.findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) view.findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}

public void createFragment(Fragment fragment) {
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.add(R.id.activity_home_container, fragment, null);
ft.addToBackStack(null);
ft.commitAllowingStateLoss();
}
}


Related Topics



Leave a reply



Submit