0

내 MainActivity 내 내부 클래스 내에서 PinnedSectionListActivity라는 내부 클래스가 있습니다. 내 조각 클래스 내에서이 PinnedSectionActivity의 인스턴스를 만들고 싶습니다. 그래서 내 프래그먼트 클래스가 인스턴스화되면 생성 된 해당 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

왜 조각을 자신의 조각에 내부 클래스로 만들고 싶습니까? – donfuxx

+0

Android 개발이 처음입니다. 어리석은 실수를하면 용서해주십시오. 나는 그것을 사용하기 전에 활동을 정의해야한다. –

+0

아니요, 문제가 왜 그렇게하고 싶은지 궁금합니다. 어쨌든, 프래그먼트의 내부 클래스로 Activity를 가지는 것은 나에게별로 의미가 없습니다. 단편은 대개 다른 상위 액티비티에서 동일한 위젯을 다시 사용하기위한 것입니다. – donfuxx

답변

1

당신이 단편에서 활동을 시작에 대해 이야기하는 경우, 명시 적 인 텐트와 함께 연주 고려 어떤 당신이 조각 내부 활동에 의해 제시보기를 개최하려는 경우, 당신은있어 http://developer.android.com/reference/android/content/Intent.html

더 말하는 이단 =] 단편은 활동의 단편을 다루기로되어있다. 활동은 사용자가 그 당시 수행중인 기능에 대한 표현 자입니다. 예 : Gmail받은 편지함은 하나의 활동이며, 메시지 및 메일 읽기 창의 슬라이딩 목록은 활동의 일부분입니다.

다음은 경험적 규칙입니다. 하나의 활동에서 다음 활동으로 넘어갈 수있는 경우, 최소한의 순차 화로 수행 할 수 있어야합니다. 큰 사용자 상태를 보는 여러 가지 방법을 관리하려고하는 경우 파편을 다루는 활동 안에 있습니다.

싱글에 대한 죽음.

gl hf!

+0

이 내부 클래스를 자체적으로 ListFragment 클래스로 변환하고 대신 호출 할 수 있습니까? –

+0

글쎄, 이것을 MVP 패턴으로 유지해 보자. 무엇을 하려는지 정확히 모르겠다.하지만 일부 프래그먼트를 관리하는 액티비티가 일부 데이터 모델을 업데이트하도록 트리거하는 인터페이스를 구현 한 다음, 귀하의 단편을지지합니다. 나는 이것이 재사용 Szymon이 참조하고 있다고 생각한다. 그리고 그들은 맞다. 이것은 평범한 예전 활동으로도 가능할 수도 있지만, UI를 조금 더 설명해야한다.] –

+0

아, 아니, 그들은 당신과 마찬가지로 재사용을 의미했다. 다른 활동에서 동일한보고/느낌을 원합니다. 맞습니다. –

1

조각 안에 액티비티 인스턴스를 저장하는 것은 좋지 않다고 생각합니다. 아주 쉽게 메모리 유출로 이어질 수 있습니다 - Context을 외부에 저장해서는 안되기 때문에 외부로 유출 될 가능성이 있습니다.

어쨌든 Fragment 클래스의 getActivity() 메서드를 호출하면 현재 단편과 연결된 작업을 가져올 수 있습니다.

또한 활동을 조각의 내부 클래스로 만들지 마십시오. 그것들을 각각의 파일 안에 각각 별도의 클래스로 유지하는 것이 가장 좋습니다.

+0

이 ListActivity를 ListFragment로 바꾸어 사용하는 것이 좋습니다. 그리고 그것은 부드러운 전환일까요? –

+0

재사용을 계획하지 않는 한 어떤 종류의 조각도 사용할 필요가 없습니다. 가능한 가장 간단한 해결책을 시도하십시오. 당신의 질문에는 그것에 대한 대답이 충분하지 않습니다. – Szymon