onbackpressed 数据未显示在片段中
Posted
技术标签:
【中文标题】onbackpressed 数据未显示在片段中【英文标题】:onback pressed data not showing in fragments 【发布时间】:2015-11-14 22:39:45 【问题描述】:我在我的应用程序中使用导航抽屉,我有 F1、F2 等片段......并且在每个 fragment
中我正在解析数据并显示在 listview
中,如果我通过我的应用程序,如 F1>F2>F3 等等..但问题是如果我从 F3 转到 F2,我在 F2 片段中的数据没有显示,并且只显示空白页,有什么问题?可以一个帮助?
我的 F1
public class Categriesdrawers extends Fragment
private ImageView drwr;
private SlidingDrawer sldrwr;
private ProgressDialog pDialog;
JSONArray categorylist=null;
private ListView listview;
private ArrayList<HashMap<String,String>> aList;
private static String INTEREST_ACCEPT_URL = "http:.ashx?action=category";
private static final String INTEREST_ACCEPT="categorylist";
private static final String INTERESTACCEPT_USER_ID="Id";
private static final String INTEREST_ACCEPT_NAME="categoryname";
private CustomAdapterCatagory adapter;
private TextView noacpt;
private ListView catlist;
@SuppressWarnings("deprecation")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
View v=inflater.inflate(R.layout.tests, container, false);
drwr=(ImageView)v.findViewById(R.id.handle);
sldrwr=(SlidingDrawer)v.findViewById(R.id.bottom);
sldrwr.open();
new LoadAlbums().execute();
sldrwr.setOnDrawerOpenListener(new OnDrawerOpenListener()
@Override
public void onDrawerOpened()
new LoadAlbums().execute();
);
catlist=(ListView)v.findViewById(R.id.substitute_list);
catlist.setOnItemClickListener(new OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
Organization tf = new Organization();
Bundle bundle = new Bundle();
tf.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.mainContent, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
);
return v;
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>>
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute()
super.onPreExecute();
pDialog = new ProgressDialog(Categriesdrawers.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
protected ArrayList<HashMap<String,String>> doInBackground(String... args)
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(INTEREST_ACCEPT_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null)
try
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
categorylist = jsonObj.getJSONArray(INTEREST_ACCEPT);
for (int i = 0; i < categorylist.length(); i++)
JSONObject c = categorylist.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(INTERESTACCEPT_USER_ID, c.getString(INTERESTACCEPT_USER_ID));
map.put(INTEREST_ACCEPT_NAME,c.getString(INTEREST_ACCEPT_NAME));
// adding HashList to ArrayList
data.add(map);
catch (JSONException e)
e.printStackTrace();
else
Log.e("ServiceHandler", "Couldn't get any data from the url");
return data;
protected void onPostExecute(ArrayList<HashMap<String,String>> result)
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
if(aList == null)
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterCatagory(getActivity(),result);
catlist.setAdapter(adapter);
else
aList.addAll(result);
adapter.notifyDataSetChanged();
主活动
public class MainActivity extends Activity
ListView mDrawerList;
RelativeLayout mDrawerPane;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private CharSequence mTitle;
ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();
private CharSequence mDrawerTitle;
ActionBar actionBar;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar=getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.argb(255, 235, 139, 36)));
mTitle = mDrawerTitle = getTitle();
mNavItems.add(new NavItem("All Post", R.drawable.allpost));
mNavItems.add(new NavItem("Categories", R.drawable.allpost));
mNavItems.add(new NavItem("All Bloggers", R.drawable.allpost));
mNavItems.add(new NavItem("About Us", R.drawable.about));
mNavItems.add(new NavItem("Rate US", R.drawable.rates));
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Populate the Navigtion Drawer with options
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3)
selectItemFromDrawer(position);
);
getActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_view, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
)
public void onDrawerClosed(View view)
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
public void onDrawerOpened(View drawerView)
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
;
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(savedInstanceState==null)
selectItemFromDrawer(0);
@Override
public boolean onCreateOptionsMenu(Menu menu)
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
@Override
public boolean onOptionsItemSelected(MenuItem item)
if (mDrawerToggle.onOptionsItemSelected(item))
return true;
// Handle action bar actions click
switch (item.getItemId())
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
private void selectItemFromDrawer(int position)
Fragment fragment=null;
switch (position)
case 0:
fragment=new AllPost();
break;
case 1:
fragment=new Categriesdrawers();
break;
case 2:
fragment=new AllBloggerList();
break;
/*case 3:
fragment=new Aboutus();
break;
*/
default:
break;
if(fragment!=null)
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mNavItems.get(position).mTitle);
mDrawerLayout.closeDrawer(mDrawerPane);
/*Fragment fragment = new PreferencesFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mNavItems.get(position).mTitle);
// Close the drawer
mDrawerLayout.closeDrawer(mDrawerPane);*/
class NavItem
String mTitle;
String mSubtitle;
int mIcon;
public NavItem(String title, int icon)
mTitle = title;
mIcon = icon;
class DrawerListAdapter extends BaseAdapter
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems)
mContext = context;
mNavItems = navItems;
@Override
public int getCount()
return mNavItems.size();
@Override
public Object getItem(int position)
return mNavItems.get(position);
@Override
public long getItemId(int position)
return 0;
@Override
public View getView(int position, View convertView, ViewGroup parent)
View view;
if (convertView == null)
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, null);
else
view = convertView;
TextView titleView = (TextView) view.findViewById(R.id.title);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText( mNavItems.get(position).mTitle );
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
@Override
protected void onPostCreate(Bundle savedInstanceState)
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
@Override
public void onConfigurationChanged(Configuration newConfig)
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
@Override
public void setTitle(CharSequence title)
mTitle = title;
getActionBar().setTitle(mTitle);
@Override
public void onBackPressed()
if (getFragmentManager().getBackStackEntryCount() > 0)
getFragmentManager().popBackStack();
else
super.onBackPressed();
【问题讨论】:
您是否将这些片段添加到后台堆栈?另外请发一些截图。 nvm 问题出在您的 F2 和 F3 上。也发布他们的代码。 F2 和 F3 片段中的代码相同 3 个类的代码相同有什么意义? O_@ 在每个片段中,我使用不同的 web 服务显示不同的数据..比如 f1 有类别,f2 有 org 等 【参考方案1】:进行分片交易时请拨打addToBackStack(null)
。
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.addToBackStack(null)
.commit();
【讨论】:
它已经在那里了..你能看到吗? 你的 MainActivity 的 selectItemFromDrawer() 函数中没有它 没有调用 addToBackStack(null)。请在我的答案中查看代码 是的,我明白了..所以需要在 switch case 之后删除该代码并将其粘贴到抽屉()函数的 selectitem 中?? 我看到它已经在该函数中,只需在其中添加“.addToBackStack()”【参考方案2】:请更新您的 OnCreateView() 如下:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
if (view != null)
if (view.getParent() != null)
((ViewGroup)view.getParent()).removeView(view);
return view;
View v=inflater.inflate(R.layout.tests, container, false);
希望对你有帮助
【讨论】:
你至少能完成它吗?view
是什么?上线 -> if (view != null)
混乱。以上是关于onbackpressed 数据未显示在片段中的主要内容,如果未能解决你的问题,请参考以下文章
在活动中使用 OnBackPressed 方法的一个片段到另一个片段
onBackPressed 上的 Android 片段 NullPointerException