因此,我一直试图在我的应用程序中实现一个特性,其中所有帖子都将被列出到片段
中的recycerview
中。但是,每当我访问getActivity().getApplicationContext()
时,它将返回null。
public class HomeFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
List<Post> posts = new ArrayList<>();
private RecyclerView postsRecyclerView;
private HomePostsAdapter pAdapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
//private Activity fragmentContext;
public HomeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pAdapter = new HomePostsAdapter(posts);
RecyclerView.LayoutManager pLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
postsRecyclerView = (RecyclerView) container.findViewById(R.id.homePostsRcyclerV);
postsRecyclerView.setLayoutManager(pLayoutManager);
postsRecyclerView.setItemAnimator(new DefaultItemAnimator());
postsRecyclerView.setAdapter(pAdapter);
populatePostsDetails();
pAdapter.notifyDataSetChanged();
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
}
}
@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);
}
private void populatePostsDetails() {
posts.add(new Post(1, "A Post: The First One", "Once upon a time, there was this useless app", "July"));
posts.add(new Post(2, "The Story begins today", "It was I the allfather who did it!", "July"));
posts.add(new Post(3, "Another POST!", "what is the point of this thing h8uh?", "July"));
posts.add(new Post(4, "Dandandan", "asdasdasdasdasdasdasdasdasdasd", "July"));
posts.add(new Post(5, "A Post: The First One", "Once upon a time, there was this useless app", "July"));
posts.add(new Post(6, "The Story begins today", "It was I the allfather who did it!", "July"));
posts.add(new Post(7, "Another POST!", "what is the point of this thing h8uh?", "July"));
posts.add(new Post(8, "Dandandan", "asdasdasdasdasdasdasdasdasdasd", "July"));
posts.add(new Post(9, "A Post: The First One", "Once upon a time, there was this useless app", "July"));
posts.add(new Post(10, "The Story begins today", "It was I the allfather who did it!", "July"));
posts.add(new Post(11, "Another POST!", "what is the point of this thing h8uh?", "July"));
posts.add(new Post(12, "Dandandan", "asdasdasdasdasdasdasdasdasdasd", "July"));
}
}
public class HomePostsAdapter extends RecyclerView.Adapter<HomePostsAdapter.CustomViewHolder>{
private List<Post> posts;
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView pTitle, pContent;
public CustomViewHolder(View view) {
super(view);
pTitle = (TextView) view.findViewById(R.id.postTitle);
pContent = (TextView) view.findViewById(R.id.postContent);
}
}
public HomePostsAdapter(List<Post> posts){
this.posts = posts;
}
@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.posts_list, parent, false);
return new CustomViewHolder(itemView);
}
@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
Post post = posts.get(position);
holder.pTitle.setText(post.getPostTitle());
holder.pContent.setText(post.getPostContent());
}
@Override
public int getItemCount() {
return posts.size();
}
}
public class Post {
int id;
String title;
String content;
String date_created;
// sets values for the posts
public Post(int p_id, String p_title, String p_content, String p_date_created) {
this.id = p_id;
this.title = p_title;
this.content = p_content;
this.date_created = p_date_created;
}
public int getPostId() {
return this.id;
}
public String getPostTitle() {
return this.title;
}
public String getPostContent() {
return this.content;
}
public String getPostDateCreated() {
return this.date_created;
}
}
03-02 23:18:03.974 3377-3377/com.example.darkestmidnight.lykeyfoods E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.darkestmidnight.lykeyfoods, PID: 3377
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
at com.example.darkestmidnight.lykeyfoods.activities.main_navigation.HomeFragment.onCreateView(HomeFragment.java:85)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
您在oncreateview()
上所做的一切(除了实际膨胀视图)都应该移到onviewcreate()
。在实际膨胀或返回布局之前,您需要调用container.findviewbyid(r.id.homePostsrCyclerv)
--实际上是在空容器中查找回收视图。
相反,您应该在oncreateview()
中返回新膨胀的视图,并将作用于视图的逻辑移动到onviewcreated()
,在这里您将获得刚刚创建的视图
。
Android片段中的和有什么区别?在片段中调用时,的行为有什么不同?
在上下文上使用方法时,我总是搞不清楚该使用哪种方法以及何时使用,即getActivity()还是getApplicationContext()。请帮我解决这个。提前谢了。
我正在使用带有片段的FragmentPagerAdapter。我的问题是,当我调用setCurrentItem时,正在加载的片段的OnCreateView方法被调用两次。但是,需要注意的是,片断不是重新创建的,而是简单地恢复的。我非常想找到一个解决方案,使OnCreateView只能被调用一次。 两次调用Android oncreateview OnCreateView多次调用/使用ActionB
getApplicationContext()和getActivity()与Android中的区别是什么?
问题内容: 为什么在我的片段中,getActivity()有效但mContext.getApplicationContext()不起作用? 我的mContext被声明并初始化为: 问题答案: getActivity()返回与片段关联的Activity。 http://developer.android.com/reference/android/app/Fragment.html#getActiv