0

我在我的MainActivity的Fragment內部類中有一個名爲PinnedSectionListActivity的內部類。我想在我的片段類中創建一個PinnedSectionActivity的實例。所以當我的fragment類被實例化時,它將返回創建的那個ListActivity的那個實例。繼續努力,但無濟於事。提前致謝。在片段類中創建活動

這是我的MainActivity。

package com.example.android.navigationdrawerexample; 

import java.util.Locale; 

import com.hb.views.PinnedSectionListView; 
import com.hb.views.PinnedSectionListView.PinnedSectionListAdapter; 
import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.app.Fragment; 
import android.app.FragmentManager; 
import android.app.ListActivity; 
import android.app.SearchManager; 
import android.content.Context; 
import android.content.Intent; 
import android.content.res.Configuration; 
import android.graphics.Color; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.v4.app.ActionBarDrawerToggle; 
import android.support.v4.view.GravityCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.view.View.OnClickListener; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.ImageView; 
import android.widget.ListView; 
import android.widget.SectionIndexer; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends Activity { 
    private DrawerLayout mDrawerLayout; 
    private ListView mDrawerList; 
    private ActionBarDrawerToggle mDrawerToggle; 

    private CharSequence mDrawerTitle; 
    private CharSequence mTitle; 
    private String[] mPlanetTitles; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     mTitle = mDrawerTitle = getTitle(); 
     mPlanetTitles = getResources().getStringArray(R.array.planets_array); 
     mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
     mDrawerList = (ListView) findViewById(R.id.left_drawer); 

     // set a custom shadow that overlays the main content when the drawer opens 
     mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); 

     // set up the drawer's list view with items and click listener 
     mDrawerList.setAdapter(new ArrayAdapter<String>(this,R.layout.drawer_list_item, mPlanetTitles)); 
     //mDrawerList.setAdapter(new ArrayAdapter<String>(this,R.layout.drawer_list_item, mPlanetTitles)); 

     mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); 

     // enable ActionBar app icon to behave as action to toggle nav drawer 
     getActionBar().setDisplayHomeAsUpEnabled(true); 
     getActionBar().setHomeButtonEnabled(true); 

     // ActionBarDrawerToggle ties together the the proper interactions 
     // between the sliding drawer and the action bar app icon 
     mDrawerToggle = new ActionBarDrawerToggle(
       this,     /* host Activity */ 
       mDrawerLayout,   /* DrawerLayout object */ 
       R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ 
       R.string.drawer_open, /* "open drawer" description for accessibility */ 
       R.string.drawer_close /* "close drawer" description for accessibility */ 
       ) { 
      public void onDrawerClosed(View view) { 
       getActionBar().setTitle(mTitle); 
       invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
      } 

      public void onDrawerOpened(View drawerView) { 
       getActionBar().setTitle(mDrawerTitle); 
       invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
      } 
     }; 
     mDrawerLayout.setDrawerListener(mDrawerToggle); 

     if (savedInstanceState == null) { 
      selectItem(0); 
     } 
    } 

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

    /* Called whenever we call invalidateOptionsMenu() */ 
    @Override 
    public boolean onPrepareOptionsMenu(Menu menu) { 
     // If the nav drawer is open, hide action items related to the content view 
     boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); 
     menu.findItem(R.id.action_websearch).setVisible(!drawerOpen); 
     return super.onPrepareOptionsMenu(menu); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // The action bar home/up action should open or close the drawer. 
     // ActionBarDrawerToggle will take care of this. 
     if (mDrawerToggle.onOptionsItemSelected(item)) { 
      return true; 
     } 
     // Handle action buttons 
     switch(item.getItemId()) { 
     case R.id.action_websearch: 
      // create intent to perform web search for this planet 
      Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); 
      intent.putExtra(SearchManager.QUERY, getActionBar().getTitle()); 
      // catch event that there's no activity to handle intent 
      if (intent.resolveActivity(getPackageManager()) != null) { 
       startActivity(intent); 
      } else { 
       Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show(); 
      } 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
     } 
    } 

    /* The click listner for ListView in the navigation drawer */ 
    private class DrawerItemClickListener implements ListView.OnItemClickListener { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      selectItem(position); 
     } 
    } 

    private void selectItem(int position) { 
     // update the main content by replacing fragments 
     Fragment fragment = new PlanetFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); 
     fragment.setArguments(args); 

     FragmentManager fragmentManager = getFragmentManager(); 
     fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); 

     // update selected item and title, then close the drawer 
     mDrawerList.setItemChecked(position, true); 
     setTitle(mPlanetTitles[position]); 
     mDrawerLayout.closeDrawer(mDrawerList); 
    } 

    @Override 
    public void setTitle(CharSequence title) { 
     mTitle = title; 
     getActionBar().setTitle(mTitle); 
    } 

    /** 
    * When using the ActionBarDrawerToggle, you must call it during 
    * onPostCreate() and onConfigurationChanged()... 
    */ 

    @Override 
    protected void onPostCreate(Bundle savedInstanceState) { 
     super.onPostCreate(savedInstanceState); 
     // Sync the toggle state after onRestoreInstanceState has occurred. 
     mDrawerToggle.syncState(); 
    } 

    @Override 
    public void onConfigurationChanged(Configuration newConfig) { 
     super.onConfigurationChanged(newConfig); 
     // Pass any configuration change to the drawer toggls 
     mDrawerToggle.onConfigurationChanged(newConfig); 
    } 

    /** 
    * Fragment that appears in the "content_frame", shows a planet 
    */ 
    public static class PlanetFragment extends Fragment { 
     public static final String ARG_PLANET_NUMBER = "planet_number"; 

     public PlanetFragment() { 
      // Empty constructor required for fragment subclasses 
     } 

     /** 
     * 
     * 
     * 
     * I WOULD LIKE TO CREATE THE PINNEDSECTION ACTIVITY 
     * WHEN THE FRAGMENT GETS INITIALIZED. WOULD I HAVE TO CREATE 
     * 
     * 
     * 
     * 
     */ 
     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_planet, container, false); 
      int i = getArguments().getInt(ARG_PLANET_NUMBER); 
      String planet = getResources().getStringArray(R.array.planets_array)[i]; 

      int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()), 
          "drawable", getActivity().getPackageName()); 
      ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId); 
      getActivity().setTitle(planet); 
      return rootView; 
     } 
    } 

    /** 
    * 
    * @author randolphgordon 
    * 
    */ 
    public class PinnedSectionListActivity extends ListActivity implements OnClickListener { 

     class SimpleAdapter extends ArrayAdapter<Item> implements PinnedSectionListAdapter { 

      private final int[] COLORS = new int[] { 
       R.color.green_light, 
       R.color.orange_light, 
       R.color.blue_light, 
       R.color.red_light }; 

      public SimpleAdapter(Context context, int resource, int textViewResourceId) { 
       super(context, resource, textViewResourceId); 

       //final int sectionsNumber = 'Z' - 'A' + 1; 
       final int sectionsNumber = 'Z' - 'A' + 1; 

       prepareSections(sectionsNumber); 

       int sectionPosition = 0, listPosition = 0; 

       for (int i=0; i< sectionsNumber; i++) { 

        String title = null; 

        final String []country = { 
          "Korean", "Japanese", "Chinese", "Cambodian", "Loas", "Taiwamese" 
        }; 


        final String [] CATEGORY = { 
         "Language", 
         "sports", 
         "love", 
         "luxury", 
         "vacation", 
         "games", 
         "home", 
         "travel", 
         "electronics", 
         "movies", 
        }; 

        switch (('A' + i)) { 
        case ('A' + 0): 
         title = country[0]; 
         break; 
        case ('A' + 1): 
         title = country[1]; 
         break; 
        case ('A' + 2): 
         title = country[2]; 
         break; 
        case ('A' + 3): 
         title = country[3]; 
         break; 
        case ('A' + 4): 
         title = country[4]; 
         break; 
        case ('A' + 5): 
         title = country[5]; 
         break; 
        default: 
         break; 
        } 

        //Create a new Item class with section header and Name 
        Item section = new Item(Item.SECTION, title + " " + i); 
        //Item section = new Item(Item.SECTION, String.valueOf((char)('A' + i))); 

        section.sectionPosition = sectionPosition; 
        section.listPosition = listPosition++; 
        onSectionAdded(section, sectionPosition); 
        add(section); 

        final int itemsNumber = CATEGORY.length; 

        //(int) Math.abs((Math.cos(2f*Math.PI/3f * sectionsNumber/(i+1f)) * 25f)); 

        // For loop to iterate the exact number of itemNumber 
        for (int j = 0;j < CATEGORY.length;j++) { 
         //Item item = new Item(Item.ITEM, section.text.toUpperCase(Locale.KOREA) + " - " + j); 
         Item item = new Item(Item.ITEM, CATEGORY[j]); 
         item.sectionPosition = sectionPosition; 
         item.listPosition = listPosition++; 
         add(item); 
        } 

        sectionPosition++; 
       } 
      } 

      protected void prepareSections(int sectionsNumber) { } 
      protected void onSectionAdded(Item section, int sectionPosition) { } 

      @Override public View getView(int position, View convertView, ViewGroup parent) { 
       TextView view = (TextView) super.getView(position, convertView, parent); 
       view.setTextColor(Color.DKGRAY); 
       view.setTag("" + position); 
       Item item = getItem(position); 
       if (item.type == Item.SECTION) { 
        //view.setOnClickListener(PinnedSectionListActivity.this); 
        view.setBackgroundColor(parent.getResources().getColor(COLORS[item.sectionPosition % COLORS.length])); 
       } 
       return view; 
      } 

      @Override public int getViewTypeCount() { 
       return 2; 
      } 

      @Override public int getItemViewType(int position) { 
       return getItem(position).type; 
      } 

      @Override 
      public boolean isItemViewTypePinned(int viewType) { 
       return viewType == Item.SECTION; 
      } 

     } 

     class Item { 

      public static final int ITEM = 0; 
      public static final int SECTION = 1; 

      public final int type; 
      public final String text; 

      public int sectionPosition; 
      public int listPosition; 

      public Item(int type, String text) { 
       this.type = type; 
       this.text = text; 
      } 

      @Override public String toString() { 
       return text; 
      } 

     } 



     class FastScrollAdapter extends SimpleAdapter implements SectionIndexer { 

      private Item[] sections; 

      public FastScrollAdapter(Context context, int resource, int textViewResourceId) { 
       super(context, resource, textViewResourceId); 
      } 

      @Override protected void prepareSections(int sectionsNumber) { 
       sections = new Item[sectionsNumber]; 
      } 

      @Override protected void onSectionAdded(Item section, int sectionPosition) { 
       sections[sectionPosition] = section; 
      } 

      @Override public Item[] getSections() { 
       return sections; 
      } 

      @Override public int getPositionForSection(int section) { 
       if (section >= sections.length) { 
        section = sections.length - 1; 
       } 
       return sections[section].listPosition; 
      } 

      @Override public int getSectionForPosition(int position) { 
       if (position >= getCount()) { 
        position = getCount() - 1; 
       } 
       return getItem(position).sectionPosition; 
      } 

     } 




     private boolean hasHeaderAndFooter; 
     private boolean isFastScroll; 
     private boolean addPadding; 
     private boolean isShadowVisible = true; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      if (savedInstanceState != null) { 
       isFastScroll = savedInstanceState.getBoolean("isFastScroll"); 
       addPadding = savedInstanceState.getBoolean("addPadding"); 
       isShadowVisible = savedInstanceState.getBoolean("isShadowVisible"); 
       hasHeaderAndFooter = savedInstanceState.getBoolean("hasHeaderAndFooter"); 
      } 
      initializeHeaderAndFooter(); 
      initializeAdapter(); 
      initializePadding(); 
     } 

     @Override 
     protected void onSaveInstanceState(Bundle outState) { 
      super.onSaveInstanceState(outState); 
      outState.putBoolean("isFastScroll", isFastScroll); 
      outState.putBoolean("addPadding", addPadding); 
      outState.putBoolean("isShadowVisible", isShadowVisible); 
      outState.putBoolean("hasHeaderAndFooter", hasHeaderAndFooter); 
     } 

     @Override 
     protected void onListItemClick(ListView l, View v, int position, long id) { 
      Item item = (Item) getListView().getAdapter().getItem(position); 
      if (item != null) { 
       Toast.makeText(this, "Item " + position + ": " + item.text, Toast.LENGTH_SHORT).show(); 
      } else { 
       Toast.makeText(this, "Item " + position, Toast.LENGTH_SHORT).show(); 
      } 
     } 

     @Override 
     public boolean onCreateOptionsMenu(Menu menu) { 
      getMenuInflater().inflate(R.menu.main, menu); 
      menu.getItem(0).setChecked(isFastScroll); 
      menu.getItem(1).setChecked(addPadding); 
      menu.getItem(2).setChecked(isShadowVisible); 
      return true; 
     } 

     @Override 
     public boolean onOptionsItemSelected(MenuItem item) { 
      switch (item.getItemId()) { 
       case R.id.action_fastscroll: 
        isFastScroll = !isFastScroll; 
        item.setChecked(isFastScroll); 
        initializeAdapter(); 
        break; 
       case R.id.action_addpadding: 
        addPadding = !addPadding; 
        item.setChecked(addPadding); 
        initializePadding(); 
        break; 
       case R.id.action_showShadow: 
        isShadowVisible = !isShadowVisible; 
        item.setChecked(isShadowVisible); 
        ((PinnedSectionListView)getListView()).setShadowVisible(isShadowVisible); 
        break; 
       case R.id.action_showHeaderAndFooter: 
        hasHeaderAndFooter = !hasHeaderAndFooter; 
        item.setChecked(hasHeaderAndFooter); 
        initializeHeaderAndFooter(); 
        break; 
      } 
      return true; 
     } 

     private void initializePadding() { 
      float density = getResources().getDisplayMetrics().density; 
      int padding = addPadding ? (int) (16 * density) : 0; 
      getListView().setPadding(padding, padding, padding, padding); 
     } 

     private void initializeHeaderAndFooter() { 
      setListAdapter(null); 
      if (hasHeaderAndFooter) { 
       ListView list = getListView(); 

       LayoutInflater inflater = LayoutInflater.from(this); 
       TextView header1 = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, list, false); 
       header1.setText("First header"); 
       list.addHeaderView(header1); 

       TextView header2 = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, list, false); 
       header2.setText("Second header"); 
       list.addHeaderView(header2); 

       TextView footer = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, list, false); 
       footer.setText("Single footer"); 
       list.addFooterView(footer); 
      } 
      initializeAdapter(); 
     } 

     @SuppressLint("NewApi") 
     private void initializeAdapter() { 
      getListView().setFastScrollEnabled(isFastScroll); 
      if (isFastScroll) { 
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
        getListView().setFastScrollAlwaysVisible(true); 
       } 
       setListAdapter(new FastScrollAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1)); 
      } else { 
       setListAdapter(new SimpleAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1)); 
      } 
     } 

     @Override 
     public void onClick(View v) { 
      Toast.makeText(this, "Item: " + v.getTag() , Toast.LENGTH_SHORT).show(); 
     } 

    } 

} 
+0

爲什麼你想在你的Fragment中有一個Activity作爲內部類? – donfuxx

+0

我是Android開發新手。如果我犯了愚蠢的錯誤,請原諒。我需要在使用它之前定義活動。 –

+0

沒有問題,只是想知道爲什麼你想這樣做。無論如何,將一個Activity作爲片段中的內部類對我來說沒有多大意義。因爲碎片通常是在不同的父活動上重新使用相同的小部件。 – donfuxx

回答

1

,如果你談論的是從一個片段展開的活動,考慮有明確意圖玩一些更 http://developer.android.com/reference/android/content/Intent.html

如果你想通過舉辦活動呈現的片段內部的視圖,你談論異端=]碎片應該處理一個活動的碎片;一項活動是該用戶當時正在執行的功能的主持人。例如您的Gmail收件箱是一項活動,那些滑動的郵件列表和郵件閱讀窗口是活動中的片段。

下面是一條經驗法則:如果您可以從一個活動傳遞到下一個活動,那麼您應該能夠以最少的序列化來完成;如果您想要管理幾種查看大用戶狀態的方法,那麼您就在一個活動中,處理碎片。

死於單身。

gl hf!

+0

是否有可能將這個內部類自己轉換爲一個ListFragment類,然後將其稱爲...? –

+0

好吧,讓我們繼續討論MVP模式:我不確定你正在嘗試做什麼,但是可能你的管理某些片段的Activity可以實現一個接口來觸發它來更新某些數據模型,然後更新一個適配器正在支持你的碎片。我認爲這是Szymon引用的重用,他們是對的,這可能只是一個普通的舊活動,但你必須解釋你的用戶界面更多=] –

+0

啊,不,他們的意思是重用,就像你在另一項活動中需要相同的外觀/感覺 - 這也是對的。 –

1

我認爲將一個活動的實例存儲在一個片段中並不是一個好主意。它可能很容易導致內存泄漏 - 您不應該在本身之外存儲Context,因爲您可能會泄漏它。

無論如何,通過調用Fragment類的getActivity()方法,您總是可以獲得當前與片段關聯的活動。

另外,不要創建活動作爲片段的內部類。最好將它們保存爲獨立的類,每個類都在它自己的文件中。

+0

您是否認爲嘗試將此ListActivity更改爲ListFragment會是一個好主意。它會是一個平穩的過渡..? –

+0

除非您打算重複使用它們,否則您可能不需要使用任何類型的碎片。嘗試最簡單的解決方案。你的問題沒有足夠的細節來回答它。 – Szymon