gpt4 book ai didi

android - 在选项卡开关中保存 fragment 状态

转载 作者:太空宇宙 更新时间:2023-11-03 11:59:42 24 4
gpt4 key购买 nike

我花了一个星期尝试解决这个问题,但没有成功。请帮助我。

我将选项卡导航与 viewpager 一起使用。这是我放置选项卡和 FragmentPagerAdapter 类的类:

 public class Detail extends SherlockFragmentActivity {

ViewPager mViewPager;

TabsAdapter mTabsAdapter;


@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);


setContentView(R.layout.activity_main);

...



ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

mViewPager = (ViewPager)findViewById(R.id.pager);

// Add the tabs
mTabsAdapter = new TabsAdapter(this, bar, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.filmtab),
FragmentFilm.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.cinematab),
FragmentCinema.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.dintornitab),
FragmentPdi.class, null);



if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab"));
}



}


@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getSupportActionBar().getSelectedNavigationIndex());
}


public static class TabsAdapter extends FragmentPagerAdapter
implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
private final Context mContext;
private final ActionBar mBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

static final class TabInfo {
private final Class<?> clss;
private final Bundle args;

TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}

public TabsAdapter(Detail activity, ActionBar bar, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mBar = bar;
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}

public void addTab(ActionBar.Tab tab, Class<? extends Fragment> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mBar.addTab(tab);
notifyDataSetChanged();
}

@Override
public int getCount() {
return mTabs.size();
}

@Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}

@Override
public void onPageSelected(int position) {
mBar.setSelectedNavigationItem(position);
}

@Override
public void onPageScrollStateChanged(int state) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {

}
}
}

3个 fragment 类都是一样的我只复制一个;在 fragment 类中,我使用异步任务下载我需要放入 View 中的数据,我在 onActivityCreated 方法中执行此操作:

public class FragmentFilm extends SherlockFragment
{

private Detail act;

private DetailedRec detail_film;
private View view;
private String a;




@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{



setRetainInstance(true);
view = inflater.inflate(R.layout.tab_film_info, container, false);

return view;
}

/*
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);


}*/


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

act = (Detail) getActivity();


}




@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new DownloadFilmDetailAsyncTask().execute();


}



private class DownloadFilmDetailAsyncTask extends AsyncTask<Void, DetailedRec, Void>
{

@Override
protected void onPreExecute() {

super.onPreExecute();


}

@Override
protected void onPostExecute(Void result) {

super.onPostExecute(result);

ProgressBar prBar = (ProgressBar)getView().findViewById(R.id.progressbar_film);
prBar.setVisibility(View.GONE);
ScrollView lay = (ScrollView)getView().findViewById(R.id.tab_filmsummary);
lay.setVisibility(View.VISIBLE);


}

@Override
protected Void doInBackground(Void... params)
{
try
{


String locale = getResources().getConfiguration().locale.getDisplayName();


JSONObject objSend = new JSONObject();
objSend.put("idFilm", act.getIdFilm());
objSend.put("cinemaId",act.getIdCinema());
int ind = locale.indexOf("(");
String locale_send = locale.substring(0, ind-1);
objSend.put("locale", locale_send);
ArrayList<String> otherCin = new ArrayList<String>(Arrays.asList(act.getOtherCinemas()));
JSONArray othCin = new JSONArray(otherCin);
objSend.put("otherCinemas", othCin );
JSONObject jsonObject = sendAndGetJSONObject(JSON_SERVER+"JsonServer?op=getFilmbyId",objSend);



DetailedRec detail_rec = new DetailedRec();
//FILM
detail_rec.setFilmId(jsonObject.getString("filmId"));
detail_rec.setName(jsonObject.getString("name"));
detail_rec.setImageUrl(jsonObject.getString("imageUrl").replace("640", "80"));
detail_rec.setActors(jsonObject.getString("actors"));
detail_rec.setGenre(jsonObject.getString("genre"));
detail_rec.setDirector(jsonObject.getString("director"));
detail_rec.setPlot(jsonObject.getString("plot"));
detail_rec.setYear(jsonObject.getString("year"));
detail_rec.setDuration(jsonObject.getString("duration"));
detail_rec.setTrailer(jsonObject.getString("trailer"));
detail_rec.setRating(jsonObject.getString("rating"));

detail_film = detail_rec;
publishProgress(detail_rec);


}
catch (IOException ignored)
{
}
catch (JSONException ignored)
{
}
return null;
}

@Override
protected void onProgressUpdate(DetailedRec... values)
{
for (final DetailedRec detail_rec : values)
{

updateViews(detail_rec);

}

}

private JSONObject getJSONObject(String url) throws IOException, MalformedURLException, JSONException
{
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();


InputStream in = conn.getInputStream();

try
{
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(in),"WINDOWS_1252"));
for (String line = r.readLine(); line != null; line = r.readLine())
{
sb.append(line);
}
return new JSONObject(sb.toString());
}
finally
{
in.close();
}
}


private JSONObject sendAndGetJSONObject(String url,JSONObject request) throws IOException, MalformedURLException, JSONException
{

HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
InputStream in=null;
try{
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity(request.toString());
se.setContentType((Header) new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
in = entity.getContent();
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(in),"WINDOWS_1252"));
for (String line = r.readLine(); line != null; line = r.readLine())
{
sb.append(line);
}
return new JSONObject(sb.toString());
}catch(Exception e){

}
finally
{
in.close();
}

return null;

}


}

private void updateViews(final DetailedRec detail_rec){
//FILM
TextView filmName = (TextView) getView().findViewById(R.id.movieTitle);
filmName.setText(detail_rec.getName().trim());
TextView actors = (TextView) getView().findViewById(R.id.movieActor);
actors.setText(detail_rec.getActors().trim());
TextView genre = (TextView) getView().findViewById(R.id.movieGenre);
genre.setText(detail_rec.getGenre().trim());
TextView director = (TextView) getView().findViewById(R.id.movieDirector);
director.setText(detail_rec.getDirector().trim());
TextView plot = (TextView) getView().findViewById(R.id.moviePlot);
plot.setText(detail_rec.getPlot().trim());
TextView year = (TextView) getView().findViewById(R.id.movieYear);
year.setText(detail_rec.getYear().trim());
TextView duration = (TextView) getView().findViewById(R.id.movieDuration);
duration.setText(detail_rec.getDuration().trim());
ImageView image = (ImageView) getView().findViewById(R.id.moviePoster);

new DownloadImagesTask(detail_rec.getImageUrl().trim().replace("80", "100")).execute(image);
//image.setImageBitmap(downloadBitmap(detail_rec.getImageUrl().trim().replace("80", "100")));
//Rating
if(detail_rec.getRating().compareTo("N/A")!=0){
RatingBar rateBar = (RatingBar)getView().findViewById(R.id.MovieRatingBar);
rateBar.setRating(Float.parseFloat(detail_rec.getRating()));
}
//Trailer
Button trailer = (Button)getView().findViewById(R.id.trailer);
if(detail_rec.getTrailer().compareTo("")!=0){
trailer.setVisibility(View.VISIBLE);
trailer.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
int index = detail_rec.getTrailer().indexOf("v=");
String videoId="";
if(index!=-1){
videoId = detail_rec.getTrailer().substring(index+2); //"Fee5vbFLYM4";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+videoId));
intent.putExtra("VIDEO_ID", videoId);
startActivity(intent);
}


}
});
}

}

}

好的,在我的应用程序中,我希望 fragment 加载一次。我解释得很好:当我启动 Detail 类时, fragment 类是实例化的,所有 3 个 fragment 中的 AsyncTask 都开始了,现在当用户从一个选项卡切换到另一个选项卡时,我希望选项卡中的 fragment 未被选中,不要丢失数据和 View ,因为现在当我从一个选项卡切换到另一个选项卡,然后返回第一个选项卡,这是重新创建的,并且再次调用了 onActivityCreated 方法!

请帮助我,我搜索了所有地方,但我没有找到解决方案!!

附言我使用 SherlockActionBar,我不知道它是否相关。抱歉我的英语不好

谢谢

最佳答案

在实例化 ViewPager 之后,添加这个

mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(3);

应该可以了!

关于android - 在选项卡开关中保存 fragment 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12938778/

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