2
public class StartActivity extends Activity {
    public static Context appContext;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        appContext = getApplicationContext();

       //ActionBar
        ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        Tab tab = actionBar.newTab().setText("First tab")
                .setTabListener(new MyTabListener<AFragment>(this, "artist", AFragment.class));
        actionBar.addTab(tab);

        tab = actionBar.newTab().setText("Second Tab")
                .setTabListener(new MyTabListener<BFragment>(this, "album", BFragment.class));
        actionBar.addTab(tab);

        try {
            // get exchange rate from xml
            DownloadXMLFile download = new DownloadXMLFile();
            download.execute(new URL("http://vietcombank.com.vn/ExchangeRates/ExrateXML.aspx"));
        } catch (Exception e) {
            System.out.println(">>>> EXCEPTION: " + e.getMessage());
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.menuitem_search:
                Toast.makeText(appContext, "search", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.menuitem_add:
                Toast.makeText(appContext, "add", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.menuitem_share:
                Toast.makeText(appContext, "share", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.menuitem_feedback:
                Toast.makeText(appContext, "feedback", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.menuitem_about:
                Toast.makeText(appContext, "about", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.menuitem_quit:
                Toast.makeText(appContext, "quit", Toast.LENGTH_SHORT).show();
                return true;
        }
        return false;
    }

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

    public void setText(String st) {
        TextView text = (TextView)findViewById(R.id.textViewGold);
        text.setText(st);
    }

    private class DownloadXMLFile extends AsyncTask<URL, Integer, String> {

        @Override
        protected String doInBackground(URL... args) {
            Document doc = null;
            String ret = "";
            StringBuilder buffer = new StringBuilder();
            try {
                URL url = args[0];

                //create the new connection
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                //and connect!
                urlConnection.connect();

                // get input stream
                InputStream inputStream = urlConnection.getInputStream();
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                doc = builder.parse(inputStream);
                Element element = doc.getDocumentElement();
                ret = element.getNodeName();

                NodeList list = element.getElementsByTagName("Exrate");

                String code = "";
                String buy = "";
                String sell = "";
                String transfer = "";
                for (int i=0; i < list.getLength(); i++) {
                    Node node = (Node)list.item(i);
                    NamedNodeMap map = node.getAttributes();
                    code = map.getNamedItem("CurrencyCode").getNodeValue();
                    buy = map.getNamedItem("Buy").getNodeValue();
                    sell = map.getNamedItem("Sell").getNodeValue();
                    transfer = map.getNamedItem("Transfer").getNodeValue();

                    buffer.append(code)
                          .append(System.getProperty ("line.separator"))
                          .append("Buy: ")
                          .append(buy)
                          .append(System.getProperty ("line.separator"))
                          .append("Sell: ")
                          .append(sell)
                          .append(System.getProperty ("line.separator"))
                          .append("Transfer: ")
                          .append(transfer)                       
                          .append(System.getProperty ("line.separator"));
                }
                ret = buffer.toString();
            } catch (Exception e) {
                System.out.println(">>>> EXCEPTION: " + e.getMessage());
            }
            return ret;
        }

        protected void onProgressUpdate(Integer... progress) {
        }

        protected void onPostExecute(String result) {
            Log.i("test", result);
            // after getting exchange successfully, set text into text view in first tab
            setText(result);
        }
    }

}



class MyTabListener<T extends Fragment> implements TabListener {
    private Fragment mFragment;
    private final Activity mActivity;
    private final String mTag;
    private final Class<T> mClass;

    /** * Constructor used each time a new tab is created. * * @param activity * The host Activity, used to instantiate the fragment * @param tag * The identifier tag for the fragment * @param clz * The fragment's Class, used to instantiate the fragment */

    public MyTabListener(Activity activity, String tag, Class<T> clz) {
      mActivity = activity;
      mTag = tag;
      mClass = clz;
    }

    /* The following are each of the ActionBar.TabListener callbacks */

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
      // Check if the fragment is already initialized
      if (mFragment == null) {
        // If not, instantiate and add it to the activity
        mFragment = Fragment.instantiate(mActivity, mClass.getName());
        ft.add(android.R.id.content, mFragment, mTag);
      } else {
        // If it exists, simply attach it in order to show it
//       ft.setCustomAnimations(android.R.animator.fade_in, R.animator.animationtest);
        ft.attach(mFragment);
      }
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
      if (mFragment != null) {
//        ft.setCustomAnimations(android.R.animator.fade_in, R.animator.test);
        ft.detach(mFragment);
      }
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    public Fragment getFragment() {
        return mFragment;
    }
}

从网络获取的数据将显示在 init 的第一个选项卡上。但是当我转到第二个选项卡然后再次切换到第一个选项卡时,数据文本将不再存在。那么我们如何在第一个选项卡中保持数据文本的一致性?请帮忙

4

1 回答 1

0

尝试使用showhide片段,而不是attachdetach在你的标签监听器中..

public void onTabSelected(Tab tab, FragmentTransaction ft) {
  // Check if the fragment is already initialized
  if (mFragment == null) {
    // If not, instantiate and add it to the activity
    mFragment = Fragment.instantiate(mActivity, mClass.getName());
    ft.add(android.R.id.content, mFragment, mTag);
  } else {
    // If it exists, simply attach it in order to show it
//       ft.setCustomAnimations(android.R.animator.fade_in, R.animator.animationtest);
    ft.show(mFragment);
  }
}

public void onTabUnselected(Tab tab, FragmentTransaction ft) {
  if (mFragment != null) {
//        ft.setCustomAnimations(android.R.animator.fade_in, R.animator.test);
    ft.hide(mFragment);
  }
}

public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

public Fragment getFragment() {
    return mFragment;
}
于 2012-10-25T08:29:05.483 回答