gpt4 book ai didi

java - 仅在滑动到时加载当前页面 - 使用 Android 页面查看器

转载 作者:太空宇宙 更新时间:2023-11-04 14:35:55 25 4
gpt4 key购买 nike

我目前正在创建一个 RSS feed 阅读应用程序,使用 android 附带的页面查看器控件。我有四个使用 fragment 加载的页面,问题是,在每个页面之间滑动时...通常应用程序会卡住几秒钟,然后才实际滑动到下一个 fragment 。

我发现,这样做的原因是页面查看器不仅加载其所在的当前 fragment ;而且还加载当前 fragment 。也是列表中的下一个 fragment ;考虑到每个 fragment 都有可能在 listView 中包含 50 多个项目,而 listView 是通过与 RSS 提要的数据连接来填充的,这意味着它正在尝试同时加载两个包含大量数据的 listView。因此,导致应用程序卡住。

我的问题是,鉴于下面的代码,我如何才能使运行更顺畅。有没有一种方法可以只加载您所在的当前 fragment ,而不加载下一个 fragment ,然后当您滑动到下一个 fragment 时...加载新 fragment 等等?

任何建议都会有帮助,如果有人愿意,我可以粘贴更多代码。

谢谢!

将 fragment 添加到 pageViewer 的代码:

    package com.example.directrssread;

import java.util.List;
import java.util.Vector;

import android.support.v4.app.Fragment;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;

public class ViewPagerFragmentActivity extends FragmentActivity{

//boolean addFirstPage = true;

/** maintains the pager adapter*/
private PagerAdapter mPagerAdapter;
/* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.viewpager);
//initialsie the pager



this.initialisePaging();
}

/**
* Initialise the fragments to be paged
*/



private void initialisePaging() {

boolean addFirstPage = ((GlobalVariables) this.getApplication()).getSomeVariable();

final ActionBar actionBar = getActionBar();// getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
final ViewPager mViewPager;
mViewPager = (ViewPager) findViewById(R.id.viewpager);

// Create a tab listener that is called when the user changes tabs.
ActionBar.TabListener tabListener = new ActionBar.TabListener() {



@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub

}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// When the tab is selected, switch to the
// corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());

}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub

}

};

for (int i = 0; i < 4; i++) {
//int curr = mViewPager.get
String currTab = "";
if (i == 0)
{
currTab = "EPL";
}

if (i == 1)
{
currTab = "Champ";
}

if (i == 2)
{
currTab = "League One";
}

if (i == 3)
{
currTab = "League Two";
}
actionBar.addTab(
actionBar.newTab()

.setText(currTab)
.setTabListener(tabListener));

}

mViewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
});


List<Fragment> fragments = new Vector<Fragment>();

fragments.add(Fragment.instantiate(this, Feed1.class.getName()));

fragments.add(Fragment.instantiate(this, Feed2.class.getName()));
fragments.add(Fragment.instantiate(this, Feed3.class.getName()));

fragments.add(Fragment.instantiate(this, Feed4.class.getName()));

// fragments.add(Fragment.instantiate(this, Tab3Fragment.class.getName()));
this.mPagerAdapter = new PagerAdapter1(super.getSupportFragmentManager(), fragments);
//
ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);
pager.setAdapter(this.mPagerAdapter);

}

}

我的 ListView 页面之一:

   package com.example.directrssread;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Feed1 extends ListFragment{

String[] URL = new String[3];
int count = 0;
String currURL = "";
View mView;

ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
//Map<Date, ArrayList> menuItems = new TreeMap<Date, ArrayList>();
Map<Date, ArrayList> sortedMap = null;
//ProgressDialog.Builder builder;
// final ProgressDialog mDialog = new ProgressDialog((ViewPagerFragmentActivity)getActivity());
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_TITLE = "title";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
static final String KEY_LINK = "link";
static final String KEY_PUBDATE = "pubDate";
static final String KEY_PUBTIME = "pubDate";


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

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.e("Feed1", "Feed1");

mView = inflater.inflate(R.layout.feed1, container, false);
return inflater.inflate(R.layout.feed1, container, false);

}

public void onActivityCreated(Bundle savedInstanceState) {
menuItems.removeAll(menuItems);
count = 0;
rssRun();
Log.e("Count", String.valueOf(menuItems.size()));
super.onActivityCreated(savedInstanceState);

}

public void rssRun()
{

Log.e("FEED1", "Running feed1");
boolean runSubstring = true;
//URL[0] = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/teams/a/arsenal/rss.xml";
URL[0] = "http://www.football365.com/premier-league/rss";
URL[1] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
//URL[2] = "http://www.skysports.com/rss/0,20514,11661,00.xml";

//URL[3] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
for (int f= 0;f < URL.length;f++)
{

try{
//Log.e("TEst1", "TEst");

XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL[f]); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
Log.e("HERE", "HERE");
//Log.e("XML", xml);

NodeList nl = doc.getElementsByTagName(KEY_ITEM);
//Log.e("NODELIST", nl.toString());
// looping through all item nodes <item>

for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
if (doc!=null)
{
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
if (count == 0)
{
currURL = "Football365";
}
if (count == 1)
{
currURL = "BBC Sport";
}
if (count == 2)
{
//currURL = "SkySports";
}

//map.remove(map);

map.put(KEY_ID, parser.getValue(e, KEY_ID));
//Get the title of the article.
map.put(KEY_NAME, parser.getValue(e, KEY_TITLE));
//Get the description of the article.
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
//Get the source e.g ' Football365'.
//String pubDate = parser.getValue(e, KEY_PUBDATE);
String pubDate = parser.getValue(e, KEY_PUBDATE);
//Parse the date and time from the main strings.
//Chop off the un-wanted parts.
//Bring them back together in one string.
String pubTime = pubDate.substring(17, pubDate.length());
String pubDateFormat = "";
pubTime = pubTime.substring(0, 5);
map.put(KEY_PUBDATE, pubTime);

pubDateFormat = pubDate.substring(0, 22);
pubDate = pubDate.substring(0, 16);

pubDate = pubDate + " " + pubTime;


SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm");
Date date = dateFormatter.parse(pubDateFormat);
dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
//Log.e("DATE", dateFormatter.format(date));
//Calendar c = Calendar.getInstance();
//String currDate
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String currDate = sdf.format(new Date());
//Log.e("CURRENT DATE", currDate);
//System.out.println(dateFormatter.format(date));
//System.out.println(sdf2.format(date));

//Log.e("TITLE", )
map.put(KEY_TITLE, currURL + " - " + pubDate);
//Add the link.
map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
//Get the publish date.
//map.put(KEY_PUBDATE, parser.getValue(e, KEY_PUBDATE));
// adding HashList to ArrayList
//10
//if (dateFormatter.format(date) == currDate)
// if (dateFormatter.format(date).substring(0, 10) == currDate.substring(0, 10))
//String input = EditTextinput.getText().toString();
//input = input.replace(" ", "");
currDate = currDate.replace(" ", "");
String rssDate = dateFormatter.format(date).replace(" ", "");
Date dt1 = dateFormatter.parse(currDate);
Date dt2 = dateFormatter.parse(rssDate);
//Log.e("TRIM CURR", currDate);
//Log.e("RSSDATE", rssDate);
//if (rssDate == currDate)
if (dt1.compareTo(dt2)==0)//== currDate)
{
menuItems.add(map);
Collections.sort(menuItems, new MapComparator(KEY_PUBTIME));
Collections.reverse(menuItems);
//sortedMap = new TreeMap<Date, ArrayList>(menuItems);
//Log.e("SAME", "THE SAME");
}
//Log.e("TRIM CURR1", currDate);
//Log.e("RSSDATE1", rssDate);
//Log.e("TEst", "TEst");
for (int q = 0;q < map.size();q++)
{
//Log.e("mene", map.get(KEY_TITLE));
}


}

}
count+=1;
}
catch(Exception e)
{
Log.e("ERROR", e.toString());
}

// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC,KEY_LINK, KEY_TITLE }, new int[] {
R.id.name, R.id.desciption, R.id.link, R.id.source});
//if (count==3)
//{

setListAdapter(adapter);
//}

// selecting single ListView item
ListView lv = getListView();

//TextView txt = getTextView();

//TextView firstName = (TextView) V.findViewById(R.id.textView1);

// TextView firstName = (TextView) findViewById(R.id.textView1);
//ListView lv = (ListView) findViewById(R.id.l)
//ListView lv = ((ListView) findViewbyId(R.id)

lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String link = ((TextView) view.findViewById(R.id.link)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();

// Starting new intent
Intent in = new Intent(getActivity().getApplication(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_LINK, link);
startActivity(in);

}
});
}


// mDialog.dismiss();
Log.e("RUN", "RSSRUN");
}

class LongOperation extends AsyncTask<String, Void, String> {
// private Main longOperationContext = null;

// public LongOperation(Main context) {

// }


protected String doInBackground(String... params) {
Log.e("FEED1", "Running feed1");
boolean runSubstring = true;
//URL[0] = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/teams/a/arsenal/rss.xml";
URL[0] = "http://www.football365.com/premier-league/rss";
URL[1] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
//URL[2] = "http://www.skysports.com/rss/0,20514,11661,00.xml";

//URL[3] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
for (int f= 0;f < URL.length;f++)
{

try{
//Log.e("TEst1", "TEst");

XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL[f]); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
Log.e("HERE", "HERE");
//Log.e("XML", xml);

NodeList nl = doc.getElementsByTagName(KEY_ITEM);
//Log.e("NODELIST", nl.toString());
// looping through all item nodes <item>

for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
if (doc!=null)
{
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
if (count == 0)
{
currURL = "Football365";
}
if (count == 1)
{
currURL = "BBC Sport";
}
if (count == 2)
{
//currURL = "SkySports";
}

//map.remove(map);

map.put(KEY_ID, parser.getValue(e, KEY_ID));
//Get the title of the article.
map.put(KEY_NAME, parser.getValue(e, KEY_TITLE));
//Get the description of the article.
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
//Get the source e.g ' Football365'.
//String pubDate = parser.getValue(e, KEY_PUBDATE);
String pubDate = parser.getValue(e, KEY_PUBDATE);
//Parse the date and time from the main strings.
//Chop off the un-wanted parts.
//Bring them back together in one string.
String pubTime = pubDate.substring(17, pubDate.length());
String pubDateFormat = "";
pubTime = pubTime.substring(0, 5);
map.put(KEY_PUBDATE, pubTime);

pubDateFormat = pubDate.substring(0, 22);
pubDate = pubDate.substring(0, 16);

pubDate = pubDate + " " + pubTime;


SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm");
Date date = dateFormatter.parse(pubDateFormat);
dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
//Log.e("DATE", dateFormatter.format(date));
//Calendar c = Calendar.getInstance();
//String currDate
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String currDate = sdf.format(new Date());
//Log.e("CURRENT DATE", currDate);
//System.out.println(dateFormatter.format(date));
//System.out.println(sdf2.format(date));

//Log.e("TITLE", )
map.put(KEY_TITLE, currURL + " - " + pubDate);
//Add the link.
map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
//Get the publish date.
//map.put(KEY_PUBDATE, parser.getValue(e, KEY_PUBDATE));
// adding HashList to ArrayList
//10
//if (dateFormatter.format(date) == currDate)
// if (dateFormatter.format(date).substring(0, 10) == currDate.substring(0, 10))
//String input = EditTextinput.getText().toString();
//input = input.replace(" ", "");
currDate = currDate.replace(" ", "");
String rssDate = dateFormatter.format(date).replace(" ", "");
Date dt1 = dateFormatter.parse(currDate);
Date dt2 = dateFormatter.parse(rssDate);
//Log.e("TRIM CURR", currDate);
//Log.e("RSSDATE", rssDate);
//if (rssDate == currDate)
if (dt1.compareTo(dt2)==0)//== currDate)
{
menuItems.add(map);
Collections.sort(menuItems, new MapComparator(KEY_PUBTIME));
Collections.reverse(menuItems);
//sortedMap = new TreeMap<Date, ArrayList>(menuItems);
//Log.e("SAME", "THE SAME");
}
//Log.e("TRIM CURR1", currDate);
//Log.e("RSSDATE1", rssDate);
//Log.e("TEst", "TEst");
for (int q = 0;q < map.size();q++)
{
//Log.e("mene", map.get(KEY_TITLE));
}


}

}
count+=1;
}
catch(Exception e)
{
Log.e("ERROR", e.toString());
}

// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC,KEY_LINK, KEY_TITLE }, new int[] {
R.id.name, R.id.desciption, R.id.link, R.id.source});
//if (count==3)
//{

setListAdapter(adapter);

//setListAdapter(adapter);
//}

// selecting single ListView item
ListView lv = getListView();

//TextView txt = getTextView();

//TextView firstName = (TextView) V.findViewById(R.id.textView1);

// TextView firstName = (TextView) findViewById(R.id.textView1);
//ListView lv = (ListView) findViewById(R.id.l)
//ListView lv = ((ListView) findViewbyId(R.id)

lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String link = ((TextView) view.findViewById(R.id.link)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();

// Starting new intent
Intent in = new Intent(getActivity().getApplication(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_LINK, link);
startActivity(in);

}
});
}
return currURL;

}


protected void onPostExecute(String result) {


}
protected void onPreExecute() {
}


protected void onProgressUpdate(Void... values) {

}

}


class MapComparator implements Comparator<Map<String, String>>
{
private final String key;

public MapComparator(String key)
{
this.key = key;
}

public int compare(Map<String, String> first,
Map<String, String> second)
{
// TODO: Null checking, both for maps and values
String firstValue = first.get(key);
String secondValue = second.get(key);
return ((String) first.get(key)).compareTo((String) second.get(key));
// return firstValue.compareTo(secondValue);
}
}


}

最佳答案

正如评论中已经说过的:我建议您使用 AsyncTask 来加载内容。遵循您需要更改的内容。 (只是一个原始概述)

以下是您的 AsyncTask 的基本外观:

class LongOperation extends AsyncTask<String, Void, Void> {

protected Void doInBackground(String... params) {
for (int f= 0;f < params.length;f++)
{

try{
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(params[f]); // getting XML
// Parse xml, add to your Map etc.
}
catch(Exception e)
{
// Handle exception
}
}
return null;
}


protected void onPostExecute(Void aVoid) {
setupListView();
}
}

请注意: 我已经更改了 AsyncTask 的参数。此外,URL 是通过参数访问的,而不是通过您全局定义的数组。

setupListView(不应成为AsyncTask 的一部分)中,您创建并设置适配器以及onItemClickListener。不要在 AsyncTaskdoInBackground 方法中执行此操作。

private void setupListView(){
ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC,KEY_LINK, KEY_TITLE }, new int[] {
R.id.name, R.id.desciption, R.id.link, R.id.source});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
// ...
};
}

为了运行 AsyncTask,您只需调用以下行,包括您不想加载的所有 URL:

  new LongOperation().execute(
"http://www.football365.com/premier-league/rss",
"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk",
"http://www.skysports.com/rss/0,20514,11661,00.xml");

并回答您的问题:“有没有办法阻止在 ViewPager 中加载下一个 Fragment?” - 否,至少据我所知。这是因为下一个 fragment 需要在滑动手势之前加载。 (否则什么都看不见)

关于java - 仅在滑动到时加载当前页面 - 使用 Android 页面查看器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25581106/

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