MainActivity.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();
}
}
}
这是我得到的错误:
无法在行add(R.id.container,new。)上解析方法add(int,etc ...) 主页())
所以基本上我创建了三个片段和一个活动。我的活动没有布局(尽管它显然有一个布局页面,它的ID是容器)。我想在活动开始时将homePage布局文件添加到容器中,但这似乎不起作用。到目前为止我只创建了布局等,现在我正在尝试添加java代码,但我不确定为什么这不起作用。
我还没有编辑任何片段的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);
}
}
答案 0 :(得分:1)
这可能是因为您的homeFragment
扩展了Fragment
来自支持库(android.support.v4.app.Fragment
),因此您的MainActivity
应使用getSupportFragmentManager()
而不是{{} 1}}这是getFragmentManager()
的一部分。