2014-02-18 5 views
1

Добрый день для всех. Я не могу понять, как получить доступ к родительскому макету фрагмента из дочернего фрагмента. Предположим, у меня есть основное действие с вкладками, определенными в ActionBar. Каждая вкладка является фрагментом. Теперь на одной из этих вкладок я снова хочу использовать вкладки (на сей раз придерживаюсь внизу). Я могу создать необходимый макет, используя классический TabHost. Каждая из этих суб-вкладок будет управляться одним и тем же классом Fragment - в буквальном смысле это должен быть простой ListView с почти такими же данными из базы данных, он будет отличаться только одним полем (полный список, «посещенные» элементы и «не посещенные»).Доступ к родительскому макету фрагмента от ребенка Фрагмент

Итак, вот мой родитель PlanFragment, который помещается на вкладках основной деятельности. Он имеет TabHost и заселяет 3 Вкладки с использованием PlanListFragment:

public class PlanFragment extends Fragment implements OnTabChangeListener { 

    protected static final String TAG = "PlanFragment"; 

    public static final String TAB_FULL = "full"; 
    public static final String TAB_VISITED = "visited"; 
    public static final String TAB_NOT_VISITED = "not_visited"; 

    private View mRoot; 
    private TabHost mTabHost; 
    private int mCurrentTab; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     mRoot = inflater.inflate(R.layout.fragment_plan, container, false); 
     mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost); 
     setupTabs(); 
     return mRoot; 
    } 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     setRetainInstance(true); 

     mTabHost.setOnTabChangedListener(this); 
     mTabHost.setCurrentTab(mCurrentTab); 
     updateTab(TAB_FULL, R.id.tab_plan_full); 
    } 

    private void setupTabs() { 
     mTabHost.setup(); 
     mTabHost.addTab(newTab(TAB_FULL, R.string.label_tab_plan_full, 
       R.id.tab_plan_full)); 
     mTabHost.addTab(newTab(TAB_VISITED, 
       R.string.label_tab_plan_visited, R.id.tab_plan_visited)); 
     mTabHost.addTab(newTab(TAB_NOT_VISITED, 
       R.string.label_tab_plan_unvisited, R.id.tab_plan_not_visited)); 
    } 

    private TabSpec newTab(String tag, int labelId, int tabContentId) { 
     TabSpec tabSpec = mTabHost.newTabSpec(tag); 
     tabSpec.setIndicator(getActivity().getString(labelId)); 
     tabSpec.setContent(tabContentId); 
     return tabSpec; 
    } 

    @Override 
    public void onTabChanged(String tabId) { 
     if(TAB_FULL.equals(tabId)) { 
      updateTab(tabId, R.id.tab_plan_full); 
      mCurrentTab = 0; 
      return; 
     } 
     if(TAB_VISITED.equals(tabId)) { 
      updateTab(tabId, R.id.tab_plan_visited); 
      mCurrentTab = 1; 
      return; 
     } 
     if(TAB_NOT_VISITED.equals(tabId)) { 
      updateTab(tabId, R.id.tab_plan_not_visited); 
      mCurrentTab = 2; 
      return; 
     } 
    } 


    private void updateTab(String tabId, int placeholder) { 
     FragmentManager fm = getFragmentManager(); 
     if (fm.findFragmentByTag(tabId) == null) { 
      PlanListFragment plan = new PlanListFragment(); 
      Bundle params = new Bundle(); 
      params.putString(PlanListFragment.TAG, tabId); 
      plan.setArguments(params); 
      fm.beginTransaction() 
        .replace(placeholder, plan, tabId) 
        .commit(); 
     } 
    } 

} 

Вот макет с TabHost:

<?xml version="1.0" encoding="utf-8"?> 
<TabHost xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/tabhost" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical" 
     android:padding="5dp" > 

     <FrameLayout 
      android:id="@android:id/tabcontent" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:padding="5dp" > 

      <FrameLayout 
       android:id="@+id/tab_plan_full" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" > 

       <include layout="@layout/plan_list" /> 
      </FrameLayout> 

      <FrameLayout 
       android:id="@+id/tab_plan_visited" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" > 

       <include layout="@layout/plan_list" /> 
      </FrameLayout> 

      <FrameLayout 
       android:id="@+id/tab_plan_not_visited" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" > 

       <include layout="@layout/plan_list" /> 
      </FrameLayout> 
     </FrameLayout> 

     <TabWidget 
      android:id="@android:id/tabs" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginBottom="-4dp" 
      android:layout_weight="0" /> 
    </LinearLayout> 

</TabHost> 

plan_list.xml включены на каждой вкладке:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/LinearLayout1" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Large Text" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

    <ListView 
     android:id="@+id/listView1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 
    </ListView> 

</LinearLayout> 

И, наконец PlanListFragment, в котором я планируйте настройку CursorAdapter для базы данных на основе параметра, переданного из родительского фрагмента. Как мне получить доступ к ListView здесь?

public class PlanListFragment extends ListFragment { 

    protected static final String TAG = "PlanListFragment"; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     Bundle params = getArguments(); 
     Log.d(TAG, params.getString(TAG)); 
     return null; 
    } 

} 

ответ

0

Теперь во время моих дальнейших исследований я нашел следующую схему работы. Параметр ключа переместился в атрибут «тег» вызова в макете. Если есть какие-либо недостатки, пожалуйста, совет.

PlanFragment.java

public class PlanFragment extends Fragment implements OnTabChangeListener { 

    protected static final String TAG = "PlanFragment"; 

    public static final String TAB_FULL = "full"; 
    public static final String TAB_VISITED = "visited"; 
    public static final String TAB_NOT_VISITED = "not_visited"; 

    private View mRoot; 
    private TabHost mTabHost; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     mRoot = inflater.inflate(R.layout.fragment_plan, container, false); 
     mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost); 
     setupTabs(); 
     return mRoot; 
    } 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     setRetainInstance(true); 

     mTabHost.setOnTabChangedListener(this); 
     mTabHost.setCurrentTab(0); 
    } 

    private void setupTabs() { 
     mTabHost.setup(); 
     mTabHost.addTab(newTab(TAB_FULL, R.string.label_tab_plan_full, 
       R.id.tab_plan_full)); 
     mTabHost.addTab(newTab(TAB_VISITED, 
       R.string.label_tab_plan_visited, R.id.tab_plan_visited)); 
     mTabHost.addTab(newTab(TAB_NOT_VISITED, 
       R.string.label_tab_plan_unvisited, R.id.tab_plan_not_visited)); 
    } 

    private TabSpec newTab(String tag, int labelId, int tabContentId) { 
     TabSpec tabSpec = mTabHost.newTabSpec(tag); 
     tabSpec.setIndicator(getActivity().getString(labelId)); 
     tabSpec.setContent(tabContentId); 
     return tabSpec; 
    } 

    @Override 
    public void onTabChanged(String tabId) { 
    } 

} 

fragment_plan.xml

<?xml version="1.0" encoding="utf-8"?> 
<TabHost xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/tabhost" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical" 
     android:padding="5dp" > 

     <FrameLayout 
      android:id="@android:id/tabcontent" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:padding="5dp" > 

      <fragment 
       android:id="@+id/tab_plan_full" 
       android:tag="plan_full" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" 
       class="com.example.collector.PlanListFragment" /> 

      <fragment 
       android:id="@+id/tab_plan_visited" 
       android:tag="plan_visited" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" 
       class="com.example.collector.PlanListFragment" /> 

      <fragment 
       android:id="@+id/tab_plan_not_visited" 
       android:tag="plan_not_visited" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" 
       class="com.example.collector.PlanListFragment" /> 
     </FrameLayout> 

     <TabWidget 
      android:id="@android:id/tabs" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginBottom="-4dp" 
      android:layout_weight="0" /> 
    </LinearLayout> 

</TabHost> 

plan_list.xml

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/FrameLayout1" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Large Text" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

    <ListView 
     android:id="@android:id/list" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 
    </ListView> 

</FrameLayout> 

PlanListFragment.java

public class PlanListFragment extends ListFragment { 

    protected static final String TAG = "PlanListFragment"; 

    public PlanListFragment() {} 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.plan_list, container, false); 

     Log.d(TAG,getTag()); 

     return view; 
    } 

} 
0

В фрагменте ребенка пытается получить доступ к родительскому фрагменту так:

ParentFragment frag = ((ParentFragment)this.getParentFragment()); 
frag.sendbutton.setVisibility(View.Visible).invalidate(); 

Здесь «послать Отправить» это кнопка в родительском фрагменте. Вы должны использовать invalidate() в дочернем фрагменте, чтобы обновить представление, если это необходимо.

+0

Что делать, если мы хотим получить строку в дочернем фрагменте без использования ссылки на открытый статический тип данных? –

+0

вы не можете получить доступ к типу данных, если он не является общедоступным в родительском фрагменте из дочернего фрагмента –

Смежные вопросы