android - 错误找不到适合于add(int,Fragment)的方法

标签 android android-fragments error-handling exception-handling

我试图在一个Activity中添加一个片段,这是代码。

public class DetailActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_detail);
            if (savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.container2, new DetailFragment()) 
                        .commit();    //Line with Error
            }
        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.detail, menu);
            return true;
        }

        @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_refresh) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
    }

这是我的DetailFragment
/**
 * A placeholder fragment containing a simple view.
 */
public class DetailFragment extends Fragment {

    public DetailFragment() {
    }

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

        View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
        return rootView;
    }
}

这是fragment_detail的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:textSize="18sp"
    android:id="@+id/fragment_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</LinearLayout>

我面临的错误是cannot resolve method 'add(int,com.example...DetailFragment)'。因为,我是android的初学者,所以也请指导我如何解决此类错误。

最佳答案

您的DetailFragment需要从android.support.v4.app.Fragment而不是Fragment扩展。像这样

public class DetailFragment extends android.support.v4.app.Fragment {

 ......
}

关于android - 错误找不到适合于add(int,Fragment)的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37467425/

相关文章:

google-apps-script - 消除Ref#引用不存在的问题

mysql - 您的 SQL 语法有误; MySql

android - Android设备通过USB线连接PC本地主机

android - 滑动布局中的按钮 SetOnClickListener NullPointerException

android - 按顺序从backstack中获取所有 fragment

java - fragment 未在家庭 Activity 中显示

spring - grpc状态未从服务器拦截器发送到客户端

android - 来自模态 BottomSheetFragment 的 BottomSheetCallback

android - 如何使工具栏中的标题居中(即使显示了工具栏后退按钮)

安卓远程查看通知