android.support.v4.app.Fragment是支持库中的Fragment类,而androidx.fragment.app.FragmentActivity是AndroidX库中的FragmentActivity类。AndroidX库是Google推出的用于替代支持库的新支持库,它提供了更好的兼容性和功能。
区别如下:
下面是使用android.support.v4.app.Fragment和androidx.fragment.app.FragmentActivity的代码示例:
使用android.support.v4.app.Fragment:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
使用androidx.fragment.app.FragmentActivity:
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
需要注意的是,如果你的项目中已经迁移到了AndroidX,那么建议使用androidx.fragment.app.Fragment和androidx.fragment.app.FragmentActivity。如果你的项目还在使用旧的支持库,可以继续使用android.support.v4.app.Fragment和android.support.v4.app.FragmentActivity。