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 の最初のタブに表示されます。しかし、2 番目のタブに移動してから最初のタブに再度切り替えると、データ テキストは表示されなくなります。では、最初のタブでデータ テキストの一貫性を保つにはどうすればよいでしょうか。助けてください

4

1 に答える 1

0

タブリスナーでandの代わりにshowandhideをフラグメントとともに使用してみてください。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 に答える