gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:03:08 27 4
gpt4 key购买 nike

我试图在一个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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com