android-fragments https://www.e-learn.cn/tag/android-fragments zh-hans Twitter Login/Authentication in Android Fragment https://www.e-learn.cn/topic/4120820 <span>Twitter Login/Authentication in Android Fragment</span> <span><span lang="" about="/user/194" typeof="schema:Person" property="schema:name" datatype="">走远了吗.</span></span> <span>2021-02-20 19:27:06</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I am trying to implement a twitter login button in a fragment in Android using Fabric. I got it to work in an activity, but cannot get it working in a fragment.</p> <p>Here is my TwitterFragment class (extends fragment)</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TwitterAuthConfig authConfig = new TwitterAuthConfig(mTWITTER_KEY, mTWITTER_SECRET); Fabric.with(super.getActivity(), new Twitter(authConfig)); View view = inflater.inflate(R.layout.twitter_fragment, container, false); loginButton = (TwitterLoginButton) view.findViewById(R.id.twitter_login_button); loginButton.setCallback(new Callback&lt;TwitterSession&gt;() { @Override public void success(Result&lt;TwitterSession&gt; result) { TwitterSession session = result.data; String msg = "@" + session.getUserName() + " logged in! (#" + session.getUserId() + ")"; Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_LONG).show(); } @Override public void failure(TwitterException exception) { Log.d("TwitterKit", "Login with Twitter failure", exception); } }); return view; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //loginButton.onActivityResult(requestCode, resultCode, data); Fragment fragment = getFragmentManager().findFragmentById(R.id.twitter_login_button); if (fragment != null) { fragment.onActivityResult(requestCode, resultCode, data); } } </code></pre> <p>And my twitter_fragment.xml </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="15dp"&gt; &lt;com.twitter.sdk.android.core.identity.TwitterLoginButton android:id="@+id/twitter_login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/&gt; &lt;/LinearLayout&gt; </code></pre> <p>I am getting this in the first 2 lines of the monitor </p> <pre><code>Authorization completed with an error com.twitter.sdk.android.core.TwitterAuthException: Authorize failed. </code></pre> <p>Any ideas what the issue is?</p> <p>Thank you,</p> <br /><h3>回答1:</h3><br /><p>I had the same issue and solved it in this way:</p> <ol><li>in MainActivity, configure Twitter and add onActivityResult function:</li> </ol><p>TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET); Fabric.with(this, new Twitter(authConfig));</p> <pre><code> @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); FragmentManager fragment = getSupportFragmentManager(); if (fragment != null) { fragment.findFragmentByTag("LoginFragment").onActivityResult(requestCode, resultCode, data); } else Log.d("Twitter", "fragment is null"); } </code></pre> <ol start="2"><li><p>in your LoginFragment let your twitter button's onActivityResult</p> <p>@Override</p> <pre><code> public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); twitterlogin.onActivityResult(requestCode, resultCode, data); } </code></pre></li> </ol><p>Hope this helps, if not you, then some others with this frustrating issue.</p> <br /><br /><br /><h3>回答2:</h3><br /><ol><li>Add the twitter authentication and secret in the main activity.</li> </ol><p>private static final String TWITTER_KEY = "Your Key";<br /> private static final String TWITTER_SECRET = "Your Secret";</p> <ol start="2"><li>Add the Twitter auth config in onCreate() method on main activity.</li> </ol><p>TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET); Fabric.with(this, new Twitter(authConfig));</p> <ol start="3"><li><p>Add the onActivityResult() method in the main Activity.</p> <p>@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data);</p> <pre><code>List&lt;Fragment&gt; allFragments = getSupportFragmentManager().getFragments(); for (Fragment fragmento : allFragments) { if (fragmento instanceof TwitterSignIn) { ((TwitterSignIn) fragmento).onActivityResult(requestCode, resultCode, data); } } </code></pre> <p>} <br /></p></li> <li>Create the object of twitter login button. <br /> 'TwitterLoginButton twitterLoginButton';<br /><br /></li> </ol><p>5&gt; Update the code in on 'onCreateView' on fragment.</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_twitter_sign_in, container, false); twitterLoginButton = (TwitterLoginButton)view.findViewById(R.id.twitterLogin); textView = (TextView) view.findViewById(R.id.textView); parentLayout = (RelativeLayout) view.findViewById(R.id.twitterFragmentParentLinearLayout); parentLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Utility.hideKeyboard(v, getContext()); } }); twitterLoginButton.setCallback(new Callback&lt;TwitterSession&gt;() { @Override public void success(Result&lt;TwitterSession&gt; result) { TwitterSession session = result.data; Twitter.getApiClient().getAccountService().verifyCredentials(true, false).enqueue(new Callback&lt;User&gt;(){ @Override public void success(Result&lt;User&gt; userResult) { try { User user = userResult.data; textView.setText("UserNmae:"+user.name+"\nEmail:"+user.email+"\nImageUrl:"+user.profileImageUrl); } catch (Exception e) { e.printStackTrace(); } } @Override public void failure(TwitterException e) { } }); String msg = "@" + session.getUserName() + " logged in! (#" + session.getUserId() + ")"; } @Override public void failure(TwitterException exception) { Log.d("TwitterKit", "Login with Twitter failure", exception); } }); return view; } </code></pre> <ol start="6"><li><p>Finally add the 'onctivityResult()' in the fragment.<br /></p> <p>@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); twitterLoginButton.onActivityResult(requestCode, resultCode, data); }</p></li> <li><p>Done, test the application it should be work.</p></li> </ol><br /><br /><p>来源:<code>https://stackoverflow.com/questions/33701652/twitter-login-authentication-in-android-fragment</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/android" hreflang="zh-hans">android</a></div> <div class="field--item"><a href="/tag/android-fragments" hreflang="zh-hans">android-fragments</a></div> <div class="field--item"><a href="/tag/twitter" hreflang="zh-hans">twitter</a></div> </div> </div> Sat, 20 Feb 2021 11:27:06 +0000 走远了吗. 4120820 at https://www.e-learn.cn Twitter Login/Authentication in Android Fragment https://www.e-learn.cn/topic/4120815 <span>Twitter Login/Authentication in Android Fragment</span> <span><span lang="" about="/user/11" typeof="schema:Person" property="schema:name" datatype="">大憨熊</span></span> <span>2021-02-20 19:26:18</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I am trying to implement a twitter login button in a fragment in Android using Fabric. I got it to work in an activity, but cannot get it working in a fragment.</p> <p>Here is my TwitterFragment class (extends fragment)</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TwitterAuthConfig authConfig = new TwitterAuthConfig(mTWITTER_KEY, mTWITTER_SECRET); Fabric.with(super.getActivity(), new Twitter(authConfig)); View view = inflater.inflate(R.layout.twitter_fragment, container, false); loginButton = (TwitterLoginButton) view.findViewById(R.id.twitter_login_button); loginButton.setCallback(new Callback&lt;TwitterSession&gt;() { @Override public void success(Result&lt;TwitterSession&gt; result) { TwitterSession session = result.data; String msg = "@" + session.getUserName() + " logged in! (#" + session.getUserId() + ")"; Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_LONG).show(); } @Override public void failure(TwitterException exception) { Log.d("TwitterKit", "Login with Twitter failure", exception); } }); return view; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //loginButton.onActivityResult(requestCode, resultCode, data); Fragment fragment = getFragmentManager().findFragmentById(R.id.twitter_login_button); if (fragment != null) { fragment.onActivityResult(requestCode, resultCode, data); } } </code></pre> <p>And my twitter_fragment.xml </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="15dp"&gt; &lt;com.twitter.sdk.android.core.identity.TwitterLoginButton android:id="@+id/twitter_login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/&gt; &lt;/LinearLayout&gt; </code></pre> <p>I am getting this in the first 2 lines of the monitor </p> <pre><code>Authorization completed with an error com.twitter.sdk.android.core.TwitterAuthException: Authorize failed. </code></pre> <p>Any ideas what the issue is?</p> <p>Thank you,</p> <br /><h3>回答1:</h3><br /><p>I had the same issue and solved it in this way:</p> <ol><li>in MainActivity, configure Twitter and add onActivityResult function:</li> </ol><p>TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET); Fabric.with(this, new Twitter(authConfig));</p> <pre><code> @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); FragmentManager fragment = getSupportFragmentManager(); if (fragment != null) { fragment.findFragmentByTag("LoginFragment").onActivityResult(requestCode, resultCode, data); } else Log.d("Twitter", "fragment is null"); } </code></pre> <ol start="2"><li><p>in your LoginFragment let your twitter button's onActivityResult</p> <p>@Override</p> <pre><code> public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); twitterlogin.onActivityResult(requestCode, resultCode, data); } </code></pre></li> </ol><p>Hope this helps, if not you, then some others with this frustrating issue.</p> <br /><br /><br /><h3>回答2:</h3><br /><ol><li>Add the twitter authentication and secret in the main activity.</li> </ol><p>private static final String TWITTER_KEY = "Your Key";<br /> private static final String TWITTER_SECRET = "Your Secret";</p> <ol start="2"><li>Add the Twitter auth config in onCreate() method on main activity.</li> </ol><p>TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET); Fabric.with(this, new Twitter(authConfig));</p> <ol start="3"><li><p>Add the onActivityResult() method in the main Activity.</p> <p>@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data);</p> <pre><code>List&lt;Fragment&gt; allFragments = getSupportFragmentManager().getFragments(); for (Fragment fragmento : allFragments) { if (fragmento instanceof TwitterSignIn) { ((TwitterSignIn) fragmento).onActivityResult(requestCode, resultCode, data); } } </code></pre> <p>} <br /></p></li> <li>Create the object of twitter login button. <br /> 'TwitterLoginButton twitterLoginButton';<br /><br /></li> </ol><p>5&gt; Update the code in on 'onCreateView' on fragment.</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_twitter_sign_in, container, false); twitterLoginButton = (TwitterLoginButton)view.findViewById(R.id.twitterLogin); textView = (TextView) view.findViewById(R.id.textView); parentLayout = (RelativeLayout) view.findViewById(R.id.twitterFragmentParentLinearLayout); parentLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Utility.hideKeyboard(v, getContext()); } }); twitterLoginButton.setCallback(new Callback&lt;TwitterSession&gt;() { @Override public void success(Result&lt;TwitterSession&gt; result) { TwitterSession session = result.data; Twitter.getApiClient().getAccountService().verifyCredentials(true, false).enqueue(new Callback&lt;User&gt;(){ @Override public void success(Result&lt;User&gt; userResult) { try { User user = userResult.data; textView.setText("UserNmae:"+user.name+"\nEmail:"+user.email+"\nImageUrl:"+user.profileImageUrl); } catch (Exception e) { e.printStackTrace(); } } @Override public void failure(TwitterException e) { } }); String msg = "@" + session.getUserName() + " logged in! (#" + session.getUserId() + ")"; } @Override public void failure(TwitterException exception) { Log.d("TwitterKit", "Login with Twitter failure", exception); } }); return view; } </code></pre> <ol start="6"><li><p>Finally add the 'onctivityResult()' in the fragment.<br /></p> <p>@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); twitterLoginButton.onActivityResult(requestCode, resultCode, data); }</p></li> <li><p>Done, test the application it should be work.</p></li> </ol><br /><br /><p>来源:<code>https://stackoverflow.com/questions/33701652/twitter-login-authentication-in-android-fragment</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/android" hreflang="zh-hans">android</a></div> <div class="field--item"><a href="/tag/android-fragments" hreflang="zh-hans">android-fragments</a></div> <div class="field--item"><a href="/tag/twitter" hreflang="zh-hans">twitter</a></div> </div> </div> Sat, 20 Feb 2021 11:26:18 +0000 大憨熊 4120815 at https://www.e-learn.cn How to know Fragment id for the fragment(s) provided by the tabbed activity template https://www.e-learn.cn/topic/4120230 <span>How to know Fragment id for the fragment(s) provided by the tabbed activity template</span> <span><span lang="" about="/user/101" typeof="schema:Person" property="schema:name" datatype="">老子叫甜甜</span></span> <span>2021-02-20 10:16:20</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I have used the tabbed activity template provided by android studio but i can't happen to find the id for the different fragments used. the template had only one .xml and .java for all three fragments. I made a few changes and made three separate .xml and .java for the three fragments. But I can't figure out how to set the id for the different fragments either from .xml or in .java and without the id I can't perform inter fragment communication.</p> <br /><h3>回答1:</h3><br /><p>Now for retrieving a fragment </p> <pre><code>Fragment f = getSupportFragmentManager().findFragmentByTag(getFragmentTag(mViewPager.getId(), mViewPager.getCurrentItem())); public static String getFragmentTag(int viewId, long id) { return "android:switcher:" + viewId + ":" + id; } </code></pre> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/39555081/how-to-know-fragment-id-for-the-fragments-provided-by-the-tabbed-activity-temp</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/android" hreflang="zh-hans">android</a></div> <div class="field--item"><a href="/tag/android-fragments" hreflang="zh-hans">android-fragments</a></div> </div> </div> Sat, 20 Feb 2021 02:16:20 +0000 老子叫甜甜 4120230 at https://www.e-learn.cn How to know Fragment id for the fragment(s) provided by the tabbed activity template https://www.e-learn.cn/topic/4120213 <span>How to know Fragment id for the fragment(s) provided by the tabbed activity template</span> <span><span lang="" about="/user/180" typeof="schema:Person" property="schema:name" datatype="">孤者浪人</span></span> <span>2021-02-20 10:12:49</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I have used the tabbed activity template provided by android studio but i can't happen to find the id for the different fragments used. the template had only one .xml and .java for all three fragments. I made a few changes and made three separate .xml and .java for the three fragments. But I can't figure out how to set the id for the different fragments either from .xml or in .java and without the id I can't perform inter fragment communication.</p> <br /><h3>回答1:</h3><br /><p>Now for retrieving a fragment </p> <pre><code>Fragment f = getSupportFragmentManager().findFragmentByTag(getFragmentTag(mViewPager.getId(), mViewPager.getCurrentItem())); public static String getFragmentTag(int viewId, long id) { return "android:switcher:" + viewId + ":" + id; } </code></pre> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/39555081/how-to-know-fragment-id-for-the-fragments-provided-by-the-tabbed-activity-temp</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/android" hreflang="zh-hans">android</a></div> <div class="field--item"><a href="/tag/android-fragments" hreflang="zh-hans">android-fragments</a></div> </div> </div> Sat, 20 Feb 2021 02:12:49 +0000 孤者浪人 4120213 at https://www.e-learn.cn RecyclerView does not update after removing an item [duplicate] https://www.e-learn.cn/topic/4120121 <span>RecyclerView does not update after removing an item [duplicate]</span> <span><span lang="" about="/user/86" typeof="schema:Person" property="schema:name" datatype="">谁说我不能喝</span></span> <span>2021-02-20 09:08:19</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><div> <aside class="s-notice s-notice__info js-post-notice mb16" role="status"><div class="grid fd-column fw-nowrap"> <div class="grid fw-nowrap"> <div class="grid--cell wmn0 fl1 lh-lg"> <div class="grid--cell fl1 lh-lg"> <b>This question already has answers here</b>: </div> </div> </div> <div class="grid--cell mb0 mt4"> How to update RecyclerView Adapter Data? <span class="question-originals-answer-count"> (13 answers) </span> </div> <div class="grid--cell mb0 mt8">Closed <span title="2021-02-18 10:47:16Z" class="relativetime">yesterday</span>.</div> </div> </aside></div> <p>I have a <code>RecyclerView</code> horizontal image slider at the bottom of a fragment. The top of the fragment shows some details. Once the user clicks on the images at the bottom, the idea is to remove that image from the image slider and display its information in the fragment. Now the information shows up but the image does not gets removed from the <code>RecyclerView</code>. Here is what I have coded in the <code>Onclick</code> of the outermost layout. I have tried all the related answers that I could find but nothing worked. They all are in the code. Please let me know what am I doing wrong or what is missing. </p> <pre><code>holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isFiltering) { mItemList.clear(); mItemList.addAll(mOriginalItemList); mItemList.remove(position);// At this point mItemList holds the correct. That is all the images but not the one that was clicked. notifyItemRemoved(position); //solution 1 notifyItemRangeRemoved(position, getItemCount()); // solution 2 notifyItemRangeRemoved(0, getItemCount()); // solution 3 notifyDataSetChanged();//solution 4 } } }); </code></pre> <p>Full Code of the adapter</p> <pre><code>public class ImageGallery16X9Adapter&lt;T extends GalleryItem&gt; extends RecyclerView.Adapter&lt;ImageGallery16X9Adapter.GalleryItemViewHolder&gt; { public enum GalleryMode { All_SAME, FIRST_DIFFERENT } private Context mContext; private BasePresenter mPresenter; private List&lt;T&gt; mItemList; private List&lt;T&gt; mOriginalItemList; private GalleryItem mFirstItem; private GalleryMode mGalleryMode; private int deviceWidth, itemWidth, marginSingle, marginDouble; private boolean isFiltering; public ImageGallery16X9Adapter(Context context, BasePresenter presenter, GalleryMode galleryMode, List&lt;T&gt; itemList, GalleryItem firstItem, boolean isFiltering) { mContext = context; mPresenter = presenter; mGalleryMode = galleryMode; mItemList = new ArrayList&lt;&gt;(itemList); mOriginalItemList = new ArrayList&lt;&gt;(itemList); mFirstItem = firstItem; deviceWidth = CommonUtils.getDeviceWidth((Activity) mContext); itemWidth = (int) (deviceWidth * 0.9); marginDouble = (int) (deviceWidth * 0.05); marginSingle = (int) (deviceWidth * 0.025); this.isFiltering = isFiltering; } @Override public GalleryItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new GalleryItemViewHolder(LayoutInflater.from(parent.getContext()). inflate(R.layout.row_image_gallery_16x9_item, parent, false)); } @Override public void onBindViewHolder(GalleryItemViewHolder holder, final int position) { RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemRowRelativeLayout.getLayoutParams(); RelativeLayout.LayoutParams rlParams = (RelativeLayout.LayoutParams) holder.itemImageView.getLayoutParams(); layoutParams.width = itemWidth; rlParams.height = (int) (layoutParams.width * Constant.HEIGHT_FACTOR_16X9); if (position == 0) { layoutParams.leftMargin = marginDouble; layoutParams.rightMargin = 0; if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) { holder.itemTitle.setVisibility(View.VISIBLE); holder.itemTitle.setText(mFirstItem.getItemTitle()); if (mFirstItem.getItemImage() != null) { Picasso.with(MyApplication.getAppContext()).load(mFirstItem.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView); } else { Picasso.with(MyApplication.getAppContext()).load(R.drawable.error_image).placeholder(R.drawable.error_image).error(R.drawable.error_image).fit().into(holder.itemImageView); } holder.itemDescription.setText(mFirstItem.getItemDescription()); } } else { if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) { if (position == mItemList.size()) { layoutParams.rightMargin = marginDouble; } else { layoutParams.rightMargin = 0; } } else { if (position == mItemList.size() - 1) { layoutParams.rightMargin = marginDouble; } else { layoutParams.rightMargin = 0; } } layoutParams.leftMargin = marginSingle; } int itemPosition = position; if (mGalleryMode == GalleryMode.FIRST_DIFFERENT &amp;&amp; position &gt; 0) { itemPosition = position - 1; T item = mItemList.get(itemPosition); holder.itemTitle.setVisibility(View.GONE); holder.itemDescription.setText(item.getItemDescription()); Picasso.with(mContext).load(item.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView); } else if (mGalleryMode == GalleryMode.All_SAME) { T item = mItemList.get(itemPosition); holder.itemTitle.setVisibility(View.GONE); holder.itemDescription.setText(item.getItemDescription()); Picasso.with(mContext).load(item.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView); } holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) { if (position == 0) { mPresenter.onItemClicked(mFirstItem); } else { mPresenter.onItemClicked(mItemList.get(position - 1)); } } else { mPresenter.onItemClicked(mItemList.get(position)); if (isFiltering) { mItemList.clear(); mItemList.addAll(mOriginalItemList); mItemList.remove(position); notifyItemRemoved(position); //solution 1 notifyItemRangeRemoved(position, getItemCount()); // solution 2 notifyItemRangeRemoved(0, getItemCount()); // solution 3 notifyDataSetChanged();//solution 4 } } } }); } @Override public int getItemCount() { if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) return mItemList.size() + 1; else return mItemList.size(); } static class GalleryItemViewHolder extends RecyclerView.ViewHolder { private final TextView itemDescription, itemTitle; private final ImageView itemImageView, itemFavoriteImageView; private final RelativeLayout itemRowRelativeLayout; public GalleryItemViewHolder(View itemView) { super(itemView); itemRowRelativeLayout = (RelativeLayout) itemView.findViewById(R.id.rl_gallery_item_row); itemImageView = (ImageView) itemView.findViewById(R.id.img_gallery_item); itemFavoriteImageView = (ImageView) itemView.findViewById(R.id.img_gallery_item_favorite); itemTitle = (TextView) itemView.findViewById(R.id.txt_gallery_item_name); itemDescription = (TextView) itemView.findViewById(R.id.txt_gallery_item_description); } } </code></pre> <p>}</p> <br /><h3>回答1:</h3><br /><p>You need to use this 3 lines to make it work</p> <pre><code>mItemList.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, mItemList.size()); </code></pre> <br /><br /><br /><h3>回答2:</h3><br /><pre><code>private void removerecyclerItem(DraftStoriesPojo list) { int current_position = allStoriesPojoList.indexOf(list); allStoriesPojoList.remove(current_position); notifyItemRemoved(current_position); notifyItemRangeChanged (current_position, getItemCount()); } </code></pre> <br /><br /><br /><h3>回答3:</h3><br /><p>Declare a method in your custom <code>RecylerView</code> like below</p> <pre><code>public void DeleteData(int position){ recordingItems.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, recordingItems.size()); } </code></pre> <p>and from <code>mainActivity</code> call</p> <pre><code>adapter.DeleteData(position); </code></pre> <br /><br /><br /><h3>回答4:</h3><br /><p>In order to have your code working you need to change Adapter constructor implementation as follows:</p> <pre><code> public RecyclerViewAdapter(Context context, List&lt;Model&gt; model) { this.context = context; this.model = model; } </code></pre> <p>Then in onActivityResult do like this:</p> <pre><code> @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 4) { listModel.clear(); listModel.addAll(repository.consDataBase(context)); recyclerViewAdapter.notifyDataSetChanged(); } } </code></pre> <br /><br /><br /><h3>回答5:</h3><br /><p>No need to do so much complicated things there,simply remove and notify </p> <pre><code>holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isFiltering) { mItemList.remove(position); notifyItemRemoved(position); } } }); </code></pre> <br /><br /><br /><h3>回答6:</h3><br /><p>Only add these two lines</p> <pre><code>mItemList.remove(position); notifyDataSetChanged(); </code></pre> <br /><br /><br /><h3>回答7:</h3><br /><p>You need to use these lines to make it work</p> <pre><code>mItemList.remove(position); notifyDataSetChanged(); </code></pre> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/45413292/recyclerview-does-not-update-after-removing-an-item</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/android" hreflang="zh-hans">android</a></div> <div class="field--item"><a href="/tag/android-fragments" hreflang="zh-hans">android-fragments</a></div> <div class="field--item"><a href="/tag/android-adapter" hreflang="zh-hans">android-adapter</a></div> <div class="field--item"><a href="/tag/android-recyclerview" hreflang="zh-hans">android-recyclerview</a></div> </div> </div> Sat, 20 Feb 2021 01:08:19 +0000 谁说我不能喝 4120121 at https://www.e-learn.cn RecyclerView does not update after removing an item [duplicate] https://www.e-learn.cn/topic/4120118 <span>RecyclerView does not update after removing an item [duplicate]</span> <span><span lang="" about="/user/204" typeof="schema:Person" property="schema:name" datatype="">徘徊边缘</span></span> <span>2021-02-20 09:07:13</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><div> <aside class="s-notice s-notice__info js-post-notice mb16" role="status"><div class="grid fd-column fw-nowrap"> <div class="grid fw-nowrap"> <div class="grid--cell wmn0 fl1 lh-lg"> <div class="grid--cell fl1 lh-lg"> <b>This question already has answers here</b>: </div> </div> </div> <div class="grid--cell mb0 mt4"> How to update RecyclerView Adapter Data? <span class="question-originals-answer-count"> (13 answers) </span> </div> <div class="grid--cell mb0 mt8">Closed <span title="2021-02-18 10:47:16Z" class="relativetime">yesterday</span>.</div> </div> </aside></div> <p>I have a <code>RecyclerView</code> horizontal image slider at the bottom of a fragment. The top of the fragment shows some details. Once the user clicks on the images at the bottom, the idea is to remove that image from the image slider and display its information in the fragment. Now the information shows up but the image does not gets removed from the <code>RecyclerView</code>. Here is what I have coded in the <code>Onclick</code> of the outermost layout. I have tried all the related answers that I could find but nothing worked. They all are in the code. Please let me know what am I doing wrong or what is missing. </p> <pre><code>holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isFiltering) { mItemList.clear(); mItemList.addAll(mOriginalItemList); mItemList.remove(position);// At this point mItemList holds the correct. That is all the images but not the one that was clicked. notifyItemRemoved(position); //solution 1 notifyItemRangeRemoved(position, getItemCount()); // solution 2 notifyItemRangeRemoved(0, getItemCount()); // solution 3 notifyDataSetChanged();//solution 4 } } }); </code></pre> <p>Full Code of the adapter</p> <pre><code>public class ImageGallery16X9Adapter&lt;T extends GalleryItem&gt; extends RecyclerView.Adapter&lt;ImageGallery16X9Adapter.GalleryItemViewHolder&gt; { public enum GalleryMode { All_SAME, FIRST_DIFFERENT } private Context mContext; private BasePresenter mPresenter; private List&lt;T&gt; mItemList; private List&lt;T&gt; mOriginalItemList; private GalleryItem mFirstItem; private GalleryMode mGalleryMode; private int deviceWidth, itemWidth, marginSingle, marginDouble; private boolean isFiltering; public ImageGallery16X9Adapter(Context context, BasePresenter presenter, GalleryMode galleryMode, List&lt;T&gt; itemList, GalleryItem firstItem, boolean isFiltering) { mContext = context; mPresenter = presenter; mGalleryMode = galleryMode; mItemList = new ArrayList&lt;&gt;(itemList); mOriginalItemList = new ArrayList&lt;&gt;(itemList); mFirstItem = firstItem; deviceWidth = CommonUtils.getDeviceWidth((Activity) mContext); itemWidth = (int) (deviceWidth * 0.9); marginDouble = (int) (deviceWidth * 0.05); marginSingle = (int) (deviceWidth * 0.025); this.isFiltering = isFiltering; } @Override public GalleryItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new GalleryItemViewHolder(LayoutInflater.from(parent.getContext()). inflate(R.layout.row_image_gallery_16x9_item, parent, false)); } @Override public void onBindViewHolder(GalleryItemViewHolder holder, final int position) { RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemRowRelativeLayout.getLayoutParams(); RelativeLayout.LayoutParams rlParams = (RelativeLayout.LayoutParams) holder.itemImageView.getLayoutParams(); layoutParams.width = itemWidth; rlParams.height = (int) (layoutParams.width * Constant.HEIGHT_FACTOR_16X9); if (position == 0) { layoutParams.leftMargin = marginDouble; layoutParams.rightMargin = 0; if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) { holder.itemTitle.setVisibility(View.VISIBLE); holder.itemTitle.setText(mFirstItem.getItemTitle()); if (mFirstItem.getItemImage() != null) { Picasso.with(MyApplication.getAppContext()).load(mFirstItem.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView); } else { Picasso.with(MyApplication.getAppContext()).load(R.drawable.error_image).placeholder(R.drawable.error_image).error(R.drawable.error_image).fit().into(holder.itemImageView); } holder.itemDescription.setText(mFirstItem.getItemDescription()); } } else { if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) { if (position == mItemList.size()) { layoutParams.rightMargin = marginDouble; } else { layoutParams.rightMargin = 0; } } else { if (position == mItemList.size() - 1) { layoutParams.rightMargin = marginDouble; } else { layoutParams.rightMargin = 0; } } layoutParams.leftMargin = marginSingle; } int itemPosition = position; if (mGalleryMode == GalleryMode.FIRST_DIFFERENT &amp;&amp; position &gt; 0) { itemPosition = position - 1; T item = mItemList.get(itemPosition); holder.itemTitle.setVisibility(View.GONE); holder.itemDescription.setText(item.getItemDescription()); Picasso.with(mContext).load(item.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView); } else if (mGalleryMode == GalleryMode.All_SAME) { T item = mItemList.get(itemPosition); holder.itemTitle.setVisibility(View.GONE); holder.itemDescription.setText(item.getItemDescription()); Picasso.with(mContext).load(item.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView); } holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) { if (position == 0) { mPresenter.onItemClicked(mFirstItem); } else { mPresenter.onItemClicked(mItemList.get(position - 1)); } } else { mPresenter.onItemClicked(mItemList.get(position)); if (isFiltering) { mItemList.clear(); mItemList.addAll(mOriginalItemList); mItemList.remove(position); notifyItemRemoved(position); //solution 1 notifyItemRangeRemoved(position, getItemCount()); // solution 2 notifyItemRangeRemoved(0, getItemCount()); // solution 3 notifyDataSetChanged();//solution 4 } } } }); } @Override public int getItemCount() { if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) return mItemList.size() + 1; else return mItemList.size(); } static class GalleryItemViewHolder extends RecyclerView.ViewHolder { private final TextView itemDescription, itemTitle; private final ImageView itemImageView, itemFavoriteImageView; private final RelativeLayout itemRowRelativeLayout; public GalleryItemViewHolder(View itemView) { super(itemView); itemRowRelativeLayout = (RelativeLayout) itemView.findViewById(R.id.rl_gallery_item_row); itemImageView = (ImageView) itemView.findViewById(R.id.img_gallery_item); itemFavoriteImageView = (ImageView) itemView.findViewById(R.id.img_gallery_item_favorite); itemTitle = (TextView) itemView.findViewById(R.id.txt_gallery_item_name); itemDescription = (TextView) itemView.findViewById(R.id.txt_gallery_item_description); } } </code></pre> <p>}</p> <br /><h3>回答1:</h3><br /><p>You need to use this 3 lines to make it work</p> <pre><code>mItemList.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, mItemList.size()); </code></pre> <br /><br /><br /><h3>回答2:</h3><br /><pre><code>private void removerecyclerItem(DraftStoriesPojo list) { int current_position = allStoriesPojoList.indexOf(list); allStoriesPojoList.remove(current_position); notifyItemRemoved(current_position); notifyItemRangeChanged (current_position, getItemCount()); } </code></pre> <br /><br /><br /><h3>回答3:</h3><br /><p>Declare a method in your custom <code>RecylerView</code> like below</p> <pre><code>public void DeleteData(int position){ recordingItems.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, recordingItems.size()); } </code></pre> <p>and from <code>mainActivity</code> call</p> <pre><code>adapter.DeleteData(position); </code></pre> <br /><br /><br /><h3>回答4:</h3><br /><p>In order to have your code working you need to change Adapter constructor implementation as follows:</p> <pre><code> public RecyclerViewAdapter(Context context, List&lt;Model&gt; model) { this.context = context; this.model = model; } </code></pre> <p>Then in onActivityResult do like this:</p> <pre><code> @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 4) { listModel.clear(); listModel.addAll(repository.consDataBase(context)); recyclerViewAdapter.notifyDataSetChanged(); } } </code></pre> <br /><br /><br /><h3>回答5:</h3><br /><p>No need to do so much complicated things there,simply remove and notify </p> <pre><code>holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isFiltering) { mItemList.remove(position); notifyItemRemoved(position); } } }); </code></pre> <br /><br /><br /><h3>回答6:</h3><br /><p>Only add these two lines</p> <pre><code>mItemList.remove(position); notifyDataSetChanged(); </code></pre> <br /><br /><br /><h3>回答7:</h3><br /><p>You need to use these lines to make it work</p> <pre><code>mItemList.remove(position); notifyDataSetChanged(); </code></pre> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/45413292/recyclerview-does-not-update-after-removing-an-item</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/android" hreflang="zh-hans">android</a></div> <div class="field--item"><a href="/tag/android-fragments" hreflang="zh-hans">android-fragments</a></div> <div class="field--item"><a href="/tag/android-adapter" hreflang="zh-hans">android-adapter</a></div> <div class="field--item"><a href="/tag/android-recyclerview" hreflang="zh-hans">android-recyclerview</a></div> </div> </div> Sat, 20 Feb 2021 01:07:13 +0000 徘徊边缘 4120118 at https://www.e-learn.cn RecyclerView does not update after removing an item [duplicate] https://www.e-learn.cn/topic/4120115 <span>RecyclerView does not update after removing an item [duplicate]</span> <span><span lang="" about="/user/146" typeof="schema:Person" property="schema:name" datatype="">狂风中的少年</span></span> <span>2021-02-20 09:07:07</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><div> <aside class="s-notice s-notice__info js-post-notice mb16" role="status"><div class="grid fd-column fw-nowrap"> <div class="grid fw-nowrap"> <div class="grid--cell wmn0 fl1 lh-lg"> <div class="grid--cell fl1 lh-lg"> <b>This question already has answers here</b>: </div> </div> </div> <div class="grid--cell mb0 mt4"> How to update RecyclerView Adapter Data? <span class="question-originals-answer-count"> (13 answers) </span> </div> <div class="grid--cell mb0 mt8">Closed <span title="2021-02-18 10:47:16Z" class="relativetime">yesterday</span>.</div> </div> </aside></div> <p>I have a <code>RecyclerView</code> horizontal image slider at the bottom of a fragment. The top of the fragment shows some details. Once the user clicks on the images at the bottom, the idea is to remove that image from the image slider and display its information in the fragment. Now the information shows up but the image does not gets removed from the <code>RecyclerView</code>. Here is what I have coded in the <code>Onclick</code> of the outermost layout. I have tried all the related answers that I could find but nothing worked. They all are in the code. Please let me know what am I doing wrong or what is missing. </p> <pre><code>holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isFiltering) { mItemList.clear(); mItemList.addAll(mOriginalItemList); mItemList.remove(position);// At this point mItemList holds the correct. That is all the images but not the one that was clicked. notifyItemRemoved(position); //solution 1 notifyItemRangeRemoved(position, getItemCount()); // solution 2 notifyItemRangeRemoved(0, getItemCount()); // solution 3 notifyDataSetChanged();//solution 4 } } }); </code></pre> <p>Full Code of the adapter</p> <pre><code>public class ImageGallery16X9Adapter&lt;T extends GalleryItem&gt; extends RecyclerView.Adapter&lt;ImageGallery16X9Adapter.GalleryItemViewHolder&gt; { public enum GalleryMode { All_SAME, FIRST_DIFFERENT } private Context mContext; private BasePresenter mPresenter; private List&lt;T&gt; mItemList; private List&lt;T&gt; mOriginalItemList; private GalleryItem mFirstItem; private GalleryMode mGalleryMode; private int deviceWidth, itemWidth, marginSingle, marginDouble; private boolean isFiltering; public ImageGallery16X9Adapter(Context context, BasePresenter presenter, GalleryMode galleryMode, List&lt;T&gt; itemList, GalleryItem firstItem, boolean isFiltering) { mContext = context; mPresenter = presenter; mGalleryMode = galleryMode; mItemList = new ArrayList&lt;&gt;(itemList); mOriginalItemList = new ArrayList&lt;&gt;(itemList); mFirstItem = firstItem; deviceWidth = CommonUtils.getDeviceWidth((Activity) mContext); itemWidth = (int) (deviceWidth * 0.9); marginDouble = (int) (deviceWidth * 0.05); marginSingle = (int) (deviceWidth * 0.025); this.isFiltering = isFiltering; } @Override public GalleryItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new GalleryItemViewHolder(LayoutInflater.from(parent.getContext()). inflate(R.layout.row_image_gallery_16x9_item, parent, false)); } @Override public void onBindViewHolder(GalleryItemViewHolder holder, final int position) { RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemRowRelativeLayout.getLayoutParams(); RelativeLayout.LayoutParams rlParams = (RelativeLayout.LayoutParams) holder.itemImageView.getLayoutParams(); layoutParams.width = itemWidth; rlParams.height = (int) (layoutParams.width * Constant.HEIGHT_FACTOR_16X9); if (position == 0) { layoutParams.leftMargin = marginDouble; layoutParams.rightMargin = 0; if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) { holder.itemTitle.setVisibility(View.VISIBLE); holder.itemTitle.setText(mFirstItem.getItemTitle()); if (mFirstItem.getItemImage() != null) { Picasso.with(MyApplication.getAppContext()).load(mFirstItem.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView); } else { Picasso.with(MyApplication.getAppContext()).load(R.drawable.error_image).placeholder(R.drawable.error_image).error(R.drawable.error_image).fit().into(holder.itemImageView); } holder.itemDescription.setText(mFirstItem.getItemDescription()); } } else { if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) { if (position == mItemList.size()) { layoutParams.rightMargin = marginDouble; } else { layoutParams.rightMargin = 0; } } else { if (position == mItemList.size() - 1) { layoutParams.rightMargin = marginDouble; } else { layoutParams.rightMargin = 0; } } layoutParams.leftMargin = marginSingle; } int itemPosition = position; if (mGalleryMode == GalleryMode.FIRST_DIFFERENT &amp;&amp; position &gt; 0) { itemPosition = position - 1; T item = mItemList.get(itemPosition); holder.itemTitle.setVisibility(View.GONE); holder.itemDescription.setText(item.getItemDescription()); Picasso.with(mContext).load(item.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView); } else if (mGalleryMode == GalleryMode.All_SAME) { T item = mItemList.get(itemPosition); holder.itemTitle.setVisibility(View.GONE); holder.itemDescription.setText(item.getItemDescription()); Picasso.with(mContext).load(item.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView); } holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) { if (position == 0) { mPresenter.onItemClicked(mFirstItem); } else { mPresenter.onItemClicked(mItemList.get(position - 1)); } } else { mPresenter.onItemClicked(mItemList.get(position)); if (isFiltering) { mItemList.clear(); mItemList.addAll(mOriginalItemList); mItemList.remove(position); notifyItemRemoved(position); //solution 1 notifyItemRangeRemoved(position, getItemCount()); // solution 2 notifyItemRangeRemoved(0, getItemCount()); // solution 3 notifyDataSetChanged();//solution 4 } } } }); } @Override public int getItemCount() { if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) return mItemList.size() + 1; else return mItemList.size(); } static class GalleryItemViewHolder extends RecyclerView.ViewHolder { private final TextView itemDescription, itemTitle; private final ImageView itemImageView, itemFavoriteImageView; private final RelativeLayout itemRowRelativeLayout; public GalleryItemViewHolder(View itemView) { super(itemView); itemRowRelativeLayout = (RelativeLayout) itemView.findViewById(R.id.rl_gallery_item_row); itemImageView = (ImageView) itemView.findViewById(R.id.img_gallery_item); itemFavoriteImageView = (ImageView) itemView.findViewById(R.id.img_gallery_item_favorite); itemTitle = (TextView) itemView.findViewById(R.id.txt_gallery_item_name); itemDescription = (TextView) itemView.findViewById(R.id.txt_gallery_item_description); } } </code></pre> <p>}</p> <br /><h3>回答1:</h3><br /><p>You need to use this 3 lines to make it work</p> <pre><code>mItemList.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, mItemList.size()); </code></pre> <br /><br /><br /><h3>回答2:</h3><br /><pre><code>private void removerecyclerItem(DraftStoriesPojo list) { int current_position = allStoriesPojoList.indexOf(list); allStoriesPojoList.remove(current_position); notifyItemRemoved(current_position); notifyItemRangeChanged (current_position, getItemCount()); } </code></pre> <br /><br /><br /><h3>回答3:</h3><br /><p>Declare a method in your custom <code>RecylerView</code> like below</p> <pre><code>public void DeleteData(int position){ recordingItems.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, recordingItems.size()); } </code></pre> <p>and from <code>mainActivity</code> call</p> <pre><code>adapter.DeleteData(position); </code></pre> <br /><br /><br /><h3>回答4:</h3><br /><p>In order to have your code working you need to change Adapter constructor implementation as follows:</p> <pre><code> public RecyclerViewAdapter(Context context, List&lt;Model&gt; model) { this.context = context; this.model = model; } </code></pre> <p>Then in onActivityResult do like this:</p> <pre><code> @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 4) { listModel.clear(); listModel.addAll(repository.consDataBase(context)); recyclerViewAdapter.notifyDataSetChanged(); } } </code></pre> <br /><br /><br /><h3>回答5:</h3><br /><p>No need to do so much complicated things there,simply remove and notify </p> <pre><code>holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isFiltering) { mItemList.remove(position); notifyItemRemoved(position); } } }); </code></pre> <br /><br /><br /><h3>回答6:</h3><br /><p>Only add these two lines</p> <pre><code>mItemList.remove(position); notifyDataSetChanged(); </code></pre> <br /><br /><br /><h3>回答7:</h3><br /><p>You need to use these lines to make it work</p> <pre><code>mItemList.remove(position); notifyDataSetChanged(); </code></pre> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/45413292/recyclerview-does-not-update-after-removing-an-item</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/android" hreflang="zh-hans">android</a></div> <div class="field--item"><a href="/tag/android-fragments" hreflang="zh-hans">android-fragments</a></div> <div class="field--item"><a href="/tag/android-adapter" hreflang="zh-hans">android-adapter</a></div> <div class="field--item"><a href="/tag/android-recyclerview" hreflang="zh-hans">android-recyclerview</a></div> </div> </div> Sat, 20 Feb 2021 01:07:07 +0000 狂风中的少年 4120115 at https://www.e-learn.cn getActivity from fragment inside View pager return null https://www.e-learn.cn/topic/4117130 <span>getActivity from fragment inside View pager return null</span> <span><span lang="" about="/user/143" typeof="schema:Person" property="schema:name" datatype="">有些话、适合烂在心里</span></span> <span>2021-02-19 06:15:11</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I have a View pager inside of Fragment Activity and the View pager Contain two fragment at the start of the activity i have a rest request and when i get the response i want to update the Views inside of each fragment and in each one i'm using getActivity but my problem is the i always get null pointer exception on getActivity just on tablet Devices but i didn't get this issue on mobile phones </p> <p>that's my pager adapter</p> <pre><code>public class Guide_ViewPager_adapter extends FragmentStatePagerAdapter { private Guides_fragment guide_frag = new Guides_fragment(); private Maps_fragment maps_frag = new Maps_fragment(); public Guide_ViewPager_adapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0: return guide_frag; case 1: return maps_frag; } return null; } @Override public int getCount() { return 2; } } </code></pre> <p>LogCat snippet:</p> <blockquote> <p>FATAL EXCEPTION: main Process: android.vi.com.vad, PID: 9554 java.lang.NullPointerException at android.vi.com.vad.Guides_fragment.update(Guides_fragment.java:138) at android.vi.com.vad.Guide_activity$GuideTask.onPostExecute(Guide_activity.java:213) at android.vi.com.vad.Guide_activity$GuideTask.onPostExecute(Guide_activity.java:165) at android.os.AsyncTask.finish(AsyncTask.java:632) at android.os.AsyncTask.access$600(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5234) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) at dalvik.system.NativeStart.main(Native Method)</p> </blockquote> <p>This is the method that i call it from inside the activity when the data loaded </p> <pre><code>public void update(String result) { if (animation != null) { animation.reset(); animation.cancel(); } if (loaderImage != null) { loaderImage.clearAnimation(); loaderImage.setVisibility(View.GONE); } if (result.equalsIgnoreCase("null")) { if (errorImage != null) { errorImage.setVisibility(View.VISIBLE); } } else { Guide_GridView_adapter adapter = new Guide_GridView_adapter(activity.getApplicationContext(), Guide_activity.Downloads_Guides); guides_gridView.setAdapter(adapter); adapter.notifyDataSetChanged(); } } </code></pre> <p>and here when I set value to activity:</p> <pre><code>@Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = getActivity(); } </code></pre> <br /><h3>回答1:</h3><br /><p>I have solved my problem by calling setRetainInstance(true) in Fragment onCreate()</p> <pre><code> @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } </code></pre> <br /><br /><br /><h3>回答2:</h3><br /><p>Why do you need to call getActivity? The activity is passed in as a parameter? ie</p> <pre><code>@Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = activity; } </code></pre> <p>Having said that if you are coding to the latest API levels onAttachActiviy(Activity) is deprecated and you should be using onAttachActivity(Context) instead</p> <p>see Android Fragment onAttach() deprecated</p> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/34157262/getactivity-from-fragment-inside-view-pager-return-null</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/android" hreflang="zh-hans">android</a></div> <div class="field--item"><a href="/tag/android-fragments" hreflang="zh-hans">android-fragments</a></div> <div class="field--item"><a href="/tag/android-viewpager" hreflang="zh-hans">android-viewpager</a></div> </div> </div> Thu, 18 Feb 2021 22:15:11 +0000 有些话、适合烂在心里 4117130 at https://www.e-learn.cn What's the proper way to setup an Android PreferenceFragment? https://www.e-learn.cn/topic/4114587 <span>What&#039;s the proper way to setup an Android PreferenceFragment?</span> <span><span lang="" about="/user/79" typeof="schema:Person" property="schema:name" datatype="">你离开我真会死。</span></span> <span>2021-02-18 21:58:24</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I'm trying to implement a basic settings activity in an Android app and either get a blank white screen or a crash. The documentation and samples I've seen aren't helping because they're either old or inconsistent. For example, depending on where you look, the settings activity should either extend Activity, PreferenceActivity, or AppCompatPreferenceActivity (part of the File&gt;New&gt;Activity&gt;Settings Activity).</p> <p>developer.android.com says you should implement the following:</p> <pre><code>public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Display the fragment as the main content. getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } } </code></pre> <p>Yet, the Settings Activity generated in Android Studio uses does not make this call for any of the three fragments it creates. It uses preference headers.</p> <p>So here are my questions:</p> <ol><li>If you're using a simple, single preferences.xml file with a single PreferenceFragment and pre-API 19 compatibility is not a requirement, what class should SettingsActivity extend? Activity, PreferenceActivity, or AppCompatPreferenceActivity (for all its support methods and delegation)?</li> <li>Do you need to call <code>getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit()</code> in SettingsActivity.onCreate()?</li> <li>With various combinations, I'm either getting a blank white settings screen with no action bar or a crash. What's the right way to setup a single PreferencesFragment within an activity that displays the app action bar?</li> </ol><br /><h3>回答1:</h3><br /><blockquote> <p>what class should SettingsActivity extend?</p> </blockquote> <p>What worked for me was extending <code>AppCompatActivity</code>.</p> <pre><code>static final String ANIMATION = "animation" ; static final String COUNTDOWN_ON_OFF = "countdown_on_off"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getFragmentManager().findFragmentById(android.R.id.content) == null) { getFragmentManager().beginTransaction().add(android.R.id.content, new Prefs()).commit(); } } </code></pre> <p>I kicked out all the generated code related to preference headers and kept some template methods/ variables (which Android Studio generated in some earlier version) for my <code>PreferenceFragment</code></p> <pre><code>public static class Prefs extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. // findPreference() uses android:key like in preferences.xml ! bindPreferenceSummaryToValue(findPreference(ANIMATION)); } } </code></pre> <p>A static method in my <code>Activity</code> class (adapted from the template). You may want to check for other preference types:</p> <pre><code> /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * * @see #sBindPreferenceSummaryToValueListener */ private static void bindPreferenceSummaryToValue(Preference preference) { // Set the listener to watch for value changes. preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); // Trigger the listener immediately with the preference's // current value. if (preference instanceof CheckBoxPreference) { sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getBoolean(preference.getKey(), true)); } else { sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getString(preference.getKey(), "")); } } </code></pre> <p>And finally, the <code>Preference.OnPreferenceChangeListener</code> as static variable in the <code>Activity</code> (also adapted from the template):</p> <pre><code> /** * A preference value change listener that updates the preference's summary * to reflect its new value.&lt;br&gt; * template by Android Studio minus Ringtone Preference */ private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object value) { String stringValue = value.toString(); if (preference instanceof ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. ListPreference listPreference = (ListPreference) preference; int index = listPreference.findIndexOfValue(stringValue); // Set the summary to reflect the new value. preference.setSummary( index &gt;= 0 ? listPreference.getEntries()[index] : null); } else if (preference instanceof RingtonePreference) { // my app didn't need that return true; } else if (preference instanceof CheckBoxPreference) { Context ctx = preference.getContext(); boolean isChecked = (Boolean) value; if (preference.getKey().equals(ANIMATION)) { preference.setSummary(isChecked ? ctx.getString(R.string.sOn) : ctx.getString(R.string.sOff)); } else if (preference.getKey().equals(COUNTDOWN_ON_OFF)) { preference.setSummary(isChecked ? ctx.getString(R.string.sWhenPaused) : ctx.getString(R.string.sNever) ); } } else { // For all other preferences, set the summary to the value's // simple string representation. preference.setSummary(stringValue); } return true; } }; } </code></pre> <br /><br /><br /><h3>回答2:</h3><br /><p>Let's say we want to have a settings screen with one checkbox preference fragment as shown below:</p> <p></p> <p>Here is a step by step guide on how to build a settings activity where you can add some preferences to toggle or change the configurations for your Android app:</p> <ol><li><p>Add a dependency for support of preference fragment in <code>build.gradle</code> file for <code>app</code> module:</p> <pre><code>dependencies { compile 'com.android.support:preference-v7:25.1.0' } </code></pre></li> <li><p>Add <code>xml</code> Android resource directory inside <code>res</code> directory.</p></li> <li><p>Inside <code>xml</code> directory, add a new <code>XML resource file</code> named <code>pref_visualizer.xml</code> as below. We're going to add one check-box preference fragment inside it.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;CheckBoxPreference android:defaultValue="true" android:key="show_base" android:summaryOff="Bass will not be shown currently." android:summaryOn="Bass will be shown currently." android:title="Show Bass" /&gt; &lt;/PreferenceScreen&gt; </code></pre> <p><code>PreferenceScreen</code> is the root tag which can hold as many preference fragments as you want. If you want to add more configurations of type list or text box then you need to add it here as a child of <code>PreferenceScreen</code> tag.</p></li> <li><p>Add a new Java class named <code>SettingsFragment</code> which will host <code>PreferenceScreen</code>. It should extend <code>PreferenceFragmentCompat</code> class as shown below:</p> <pre><code>import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.support.v7.preference.CheckBoxPreference; import android.support.v7.preference.EditTextPreference; import android.support.v7.preference.ListPreference; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceFragmentCompat; import android.support.v7.preference.PreferenceScreen; import android.widget.Toast; public class SettingsFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle bundle, String s) { addPreferencesFromResource(R.xml.pref_visualizer); } } </code></pre></li> <li><p>Now comes the final part where we build the association between an activity in the app and <code>SettingsFragment</code> class which hosts <code>PreferenceScreen</code>. Add a new activity named <code>SettingsActivity</code> which inherits from <code>AppCompatActivity</code> class. <code>SettingsActivity</code> class will act as the container for <code>PreferenceScreen</code>.</p></li> </ol><p>Java file for <code>SettingsActivity</code>:</p> <pre><code>import android.support.v4.app.NavUtils; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MenuItem; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); } } </code></pre> <p>Layout file for <code>SettingsActivity</code> is shown below (<code>activity_settings.xml</code>). Here <code>android.name</code> property is the crux. It connects this activity to any of the classes present in your entire project which are inheriting from <code>PreferenceFragmentCompat</code> class. I had only one such class named <code>SettingsFragment</code>. You might have more than one class inheriting from <code>PreferenceFragmentCompat</code> class if you app has multiple settings screen.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_settings" android:name="android.example.com.visualizerpreferences.SettingsFragment" android:layout_width="match_parent" android:layout_height="match_parent"/&gt; </code></pre> <p>You're all set!</p> <br /><br /><br /><h3>回答3:</h3><br /><p>Here's on Kotlin and android-x :</p> <p>gradle:</p> <pre><code>implementation 'androidx.appcompat:appcompat:1.1.0-rc01' implementation 'androidx.core:core-ktx:1.2.0-alpha02' implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta2' implementation 'com.google.android.material:material:1.1.0-alpha08' implementation "androidx.preference:preference-ktx:1.1.0-rc01" implementation 'androidx.core:core-ktx:1.2.0-alpha02' implementation 'androidx.collection:collection-ktx:1.1.0' implementation 'androidx.fragment:fragment-ktx:1.2.0-alpha01' </code></pre> <p><strong>MainActivity.kt</strong></p> <pre><code>class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) supportFragmentManager.commit { replace(android.R.id.content, PrefsFragment()) } } class PrefsFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) } } } </code></pre> <p><strong>preferences.xml</strong></p> <pre><code>&lt;androidx.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;androidx.preference.Preference android:title="hello"/&gt; &lt;/androidx.preference.PreferenceScreen&gt; </code></pre> <br /><br /><br /><h3>回答4:</h3><br /><p>In addition to answer given by RBT, a Preference Theme must be specified otherwise the app will crash with an <strong>IllegalStateException</strong>.</p> <p>In <strong>styles.xml</strong> file, just add the following line in Activity’s theme</p> <pre><code>&lt;item name="preferenceTheme"&gt;@style/PreferenceThemeOverlay&lt;/item&gt; </code></pre> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/45066520/whats-the-proper-way-to-setup-an-android-preferencefragment</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/android" hreflang="zh-hans">android</a></div> <div class="field--item"><a href="/tag/android-fragments" hreflang="zh-hans">android-fragments</a></div> <div class="field--item"><a href="/tag/android-actionbar" hreflang="zh-hans">android-actionbar</a></div> <div class="field--item"><a href="/tag/settings" hreflang="zh-hans">settings</a></div> <div class="field--item"><a href="/tag/preferences" hreflang="zh-hans">preferences</a></div> </div> </div> Thu, 18 Feb 2021 13:58:24 +0000 你离开我真会死。 4114587 at https://www.e-learn.cn DialogFragment.dismiss crashing with NullPointerException https://www.e-learn.cn/topic/4112217 <span>DialogFragment.dismiss crashing with NullPointerException</span> <span><span lang="" about="/user/103" typeof="schema:Person" property="schema:name" datatype="">ε祈祈猫儿з</span></span> <span>2021-02-18 08:54:41</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I'm doing some background work and showing a DialogFragment while I do that. Once my work is done and the relevant callback is invoked, I dismiss the dialog. When I do, I get a crash caused by a NPE in the android source, here: </p> <pre><code>void dismissInternal(boolean allowStateLoss) { if (mDialog != null) { mDialog.dismiss(); mDialog = null; } mRemoved = true; if (mBackStackId &gt;= 0) { getFragmentManager().popBackStack(mBackStackId, FragmentManager.POP_BACK_STACK_INCLUSIVE); mBackStackId = -1; } else { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.remove(this); if (allowStateLoss) { ft.commitAllowingStateLoss(); } else { ft.commit(); } } } </code></pre> <p>specifically at the line: <code>FragmentTransaction ft = getFragmentManager().beginTransaction();</code></p> <br /><h3>回答1:</h3><br /><p>This may also occur when you call dismiss() before you have called show() like Sogger said.</p> <p>After Dialog object is constructed but before dialog is not showed, if (mDialog != null) can be passed and NullPointerException will occur.</p> <p>When you check if mDialog is null or not,</p> <pre><code>if (mDialog != null) { mDialog.dismiss(); mDialog = null; } </code></pre> <p>Add more conditions like below,</p> <pre><code>if ((mDialog != null) &amp;&amp; mDialog.isAdded() &amp;&amp; mDialog.isResumed()) { mDialog.dismiss(); mDialog = null; } </code></pre> <p>I think that mDialog.isAdded() condition might be enough...</p> <br /><br /><br /><h3>回答2:</h3><br /><p>Simplest solution is to check "getFragmentManager()" for "null" before calling "dismiss()" method. Also you can extend "DialogFragment" class and override method "dismiss()" to check it there:</p> <pre><code>@Override public void dismiss() { if (getFragmentManager() != null) super.dismiss(); } </code></pre> <br /><br /><br /><h3>回答3:</h3><br /><p>I know this message is old but I ran into a similar case that I needed to solvew without refactoring or changing a lot of code. Hope it's useful for somebody</p> <pre><code> package com.example.playback; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SaferDialogFragment extends DialogFragment { private boolean allowStateLoss = false; private boolean shouldDismiss = false; public SaferDialogFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public void onStart() { super.onStart(); //check if we should dismiss the dialog after rotation if (shouldDismiss) { if (allowStateLoss) dismissAllowingStateLoss(); else dismiss(); } } @Override public void dismiss() { if (getActivity() != null) { // it's "safer" to dismiss shouldDismiss = false; super.dismiss(); } else { shouldDismiss = true; allowStateLoss = false; } } @Override public void dismissAllowingStateLoss() { if (getActivity() != null) { // it's "safer" to dismiss shouldDismiss = false; super.dismissAllowingStateLoss(); } else allowStateLoss = shouldDismiss = true; } //keeping dialog after rotation @Override public void onDestroyView() { if (getDialog() != null &amp;&amp; getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /** omitted code **/ return super.onCreateView(inflater, container, savedInstanceState); } } </code></pre> <br /><br /><br /><h3>回答4:</h3><br /><p>My bet would be that the code you posted is from the background thread... you aren't allowed to update the UI from anywhere other than the UI thread. </p> <p>You can use onPostExecute() or runOnUiThread() to achieve your goal (if my guess is right about what is happening)</p> <br /><br /><br /><h3>回答5:</h3><br /><p>Checking if it's Visible before dimissing could avoid this null pointer exception </p> <pre><code> if (mDialog != null &amp;&amp; mDialog.isVisible) { mDialog.dismiss(); mDialog = null; } </code></pre> <br /><br /><br /><h3>回答6:</h3><br /><p>The callback which is invoked is probably on the activity which is or should be destroyed (after orientation change), also the progress dialog might have been instantiated with that same activity. This might cause the NPE. Callbacks on activities should not be invoked from background tasks, to prevent these kinds of problems. Decouple the background task from the activity, for example using otto, or prevent the background task from invoking the (to be) destroyed activity. </p> <p>This is some code of mine:</p> <p>static inner class of activity:</p> <pre><code> public static class ProgressDialogFragment extends DialogFragment { ProgressDialog dialog; public ProgressDialogFragment() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { dialog = new ProgressDialog(getActivity(), getTheme()); dialog.setTitle(getString(R.string.please_wait)); dialog.setMessage(getString(R.string.uploading_picture)); dialog.setIndeterminate(true); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); return dialog; } } </code></pre> <p>Otto subscription in activity:</p> <pre><code>@Subscribe public void onUploadEvent(UploadAvatarEvent uploadAvatarEvent) { switch (uploadAvatarEvent.state) { case UploadAvatarEvent.STATE_UPLOADING: if (!mProgressDialog.isAdded()) { mProgressDialog.show(getFragmentManager(), TAG_PROGRESS_DIALOG); } break; case UploadAvatarEvent.STATE_UPLOAD_SUCCES: mProgressDialog.dismiss(); break; case UploadAvatarEvent.STATE_UPLOAD_ERROR: mProgressDialog.dismiss(); break; } } </code></pre> <p>onCreate() in activity:</p> <pre><code> mProgressDialog = (ProgressDialogFragment) getFragmentManager().findFragmentByTag(TAG_PROGRESS_DIALOG); if (mProgressDialog == null) { mProgressDialog = new ProgressDialogFragment(); } </code></pre> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/10526743/dialogfragment-dismiss-crashing-with-nullpointerexception</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/android" hreflang="zh-hans">android</a></div> <div class="field--item"><a href="/tag/android-fragments" hreflang="zh-hans">android-fragments</a></div> </div> </div> Thu, 18 Feb 2021 00:54:41 +0000 ε祈祈猫儿з 4112217 at https://www.e-learn.cn