gpt4 book ai didi

java - 将 fragment 设置为 Activity 开始时的布局

转载 作者:行者123 更新时间:2023-11-30 01:09:34 26 4
gpt4 key购买 nike

主要 Activity .java:

public class MainActivity extends AppCompatActivity  {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new homePage())
.commit();
}
}
}

这是我得到的错误:

Cannot resolve method add(int, etc...) on line add(R.id.container, new homePage())

基本上我创建了三个 fragment 和一个 Activity 。我的 Activity 没有布局(虽然它显然有布局页面,但它的 ID 是容器)。我想在 Activity 开始时将主页布局文件添加到容器中,但这似乎不起作用。到目前为止,我只创建了布局等,现在我正在尝试添加 Java 代码,但我不确定为什么这不起作用。

我还没有编辑任何 fragment 的 java 代码,所以它基本上是 android studio 在创建时添加的代码。

public class homePage extends Fragment {

private OnFragmentInteractionListener mListener;
private View view;

public homePage() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home_page, container, false);
Button btnLogin = (Button) view.findViewById(R.id.login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loginView();
}
});
return view;
}

public static homePage newInstance() {
homePage fragment = new homePage();
Bundle args = new Bundle();
return fragment;
}

public void loginView(){}

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}

最佳答案

这可能是因为您的 homeFragment 从支持库 (android.support.v4.app.Fragment) 扩展了 Fragment,因此你的 MainActivity 应该使用 getSupportFragmentManager() 而不是 getFragmentManager() 它是 android.app.Fragment 的一部分.

关于java - 将 fragment 设置为 Activity 开始时的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38553165/

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