【问题标题】:how to use getSupportFragmentManager() in Activity如何在 Activity 中使用 getSupportFragmentManager()
【发布时间】:2016-08-11 21:01:55
【问题描述】:

当我改变时

public class Bmr extends Activity implements View.OnClickListener {

public class Bmr extends appcompatactivity implements View.OnClickListener {

这个getSupportFragmentManager() 正在工作,但我需要使用Activity 类。有什么办法吗?

【问题讨论】:

  • 没有。你不能。而你为什么要Activity而不是appcompatactivity呢? Activity 是 appcompatactivity 的父级,所以你会得到所有的 Activity 方法。

标签: android android-fragments


【解决方案1】:

不能getSupportFragmentManager() 仅在 FragmentActivity 和扩展它的类中可用。

docs可以看出,AppCompatActivity是一个Activity,所以Activity中的所有东西也可以在AppCompatActivity中使用。

java.lang.Object
   ↳    android.content.Context
       ↳    android.content.ContextWrapper
           ↳    android.view.ContextThemeWrapper
               ↳    android.app.Activity
                   ↳    android.support.v4.app.FragmentActivity
                       ↳    android.support.v7.app.AppCompatActivity

【讨论】:

    【解决方案2】:

    首先如上所述你需要使用 AppcompatActivity

        public class MainActivity extends AppCompatActivity {
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                FragmentManager fm=getSupportFragmentManager();
                FragmentTransaction ft= fm.beginTransaction();
                ft.replace(R.id.mainframe,tab1Fragment);
                ft.commit();
             }
    }
    

    这是我的 activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp">
     <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/mainframe"></FrameLayout>
    
    </LinearLayout>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-28
      • 2013-01-25
      • 2017-07-06
      • 2018-03-01
      • 2013-12-29
      • 2022-11-24
      • 1970-01-01
      • 2013-12-12
      相关资源
      最近更新 更多