4

У меня есть простое приложение для Android с вкладками, настроенными с помощью Tabhost и Fragments. На одной из страниц вкладок фрагмент представляет собой список. То, что я хочу сделать, - это когда пользователь нажимает на один из элементов списка, открывайте новое представление с более конкретной информацией на основе щелчка, но сохраняя его, чтобы вкладки все еще были там.Android Fragment, нет просмотра для id внутри TabHost

Мой подход заключается в том, когда пользователь нажимает на элемент в представлении списка, создается новый фрагмент, а затем из моего основного класса FragmentActivity, который владеет всеми этими фрагментами и обрабатывает логику табуляции, он будет отделять отображаемый в данный момент фрагмент и добавьте этот «новый» (singleStationListItem) фрагмент. Проблема, с которой я сталкиваюсь, заключается в том, что я не могу добавить свой новый фрагмент к фрагментному взаимодействию с содержимым R.id.realtabcontent и, таким образом, он не будет правильно добавлен. Я получаю:

03-21 10: 50: 01,862: E/FragmentManager (1136): вид Не найдено для ид 0x1010000 (Android: атр/тема) для фрагмента singleStationListItem {40d090a0 # 2 Идентификатор = 0x1010000}

где R.id.realtabcontent = 0x01010000;

Я могу прикрепить его без Идентификатора, но тогда пользователи не могут вернуться (вызов addtobackstash()). Я искал эти ошибки, но другие решения не относятся к tabhost, и я, кажется, делаю то, что требуется, например call SetContextView (...) в onCreate() в XML-файле макета, который содержит тег framelayout, который я пытаясь прикрепить мой фрагмент. Я могу добавить фрагменты вкладки в файл R.id.realtabcontent без проблем. Кто-нибудь знает, что может вызвать мою ошибку и как я могу это исправить?

Примечание: Я следую этому руководству, чтобы заставить мои вкладки работать. Мой код очень похож. http://thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/

Мой код: activiy_main.xml

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

    <TabHost 
     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" > 

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

      <FrameLayout 
       android:id="@+android:id/realtabcontent" <--id that I want to set to 
       android:layout_width="fill_parent" 
       android:layout_height="0dp" 
       android:layout_weight="1" /> 

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

main_activity.java // части из моего фрагмента класса активности

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // Step 1: Inflate layout 
     setContentView(R.layout.activity_main); 
     // Step 2: Setup TabHost 
     initialiseTabHost(savedInstanceState); 
     if (savedInstanceState != null) { 
      mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); //set the tab as per the saved state 
     } 
    } 

public void onTabChanged(String tag) { //handles tab changes 
    TabInfo newTab = (TabInfo) this.mapTabInfo.get(tag); 
    if (mLastTab != newTab) { 
     FragmentTransaction ft =  this.getSupportFragmentManager().beginTransaction(); 
     if (mLastTab != null) { 
      if (mLastTab.fragment != null) { 
       ft.detach(mLastTab.fragment); 
      } 
     } 
     if (newTab != null) { 
      if (newTab.fragment == null) { 
       newTab.fragment = Fragment.instantiate(this, 
         newTab.clss.getName(), newTab.args); 
       ft.add(R.id.realtabcontent, newTab.fragment, newTab.tag); //note it uses the R.id.realtabcontent without any issues here 
      } else { 
       ft.attach(newTab.fragment); 
      } 
     } 

     Log.d("fragment manager in activity: ", "" + ft.isEmpty()); 
     mLastTab = newTab; 
     ft.commit(); 
     this.getSupportFragmentManager().executePendingTransactions(); 
     Log.d("ft ID: ", ft.toString()); 
    } 
} 

//This is the callback function inside the listview fragment. I created an interface and it is overwritten in here as suggested by the Android SDK guide 
public void onStationSelected(String station) { 
    FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction(); 
    ft.addToBackStack(null); 
    ft.addToBackStack(null); 

    //create argument for new fragment that will be created 
    Bundle b = new Bundle(); 
    b.putString("station", station); 
    Fragment displayStationInfo = Fragment.instantiate(this, singleStationListItem.class.getName(), b); 

    Fragment cur = getSupportFragmentManager().findFragmentById(R.id.realtabcontent); 
    ft.detach(cur); 
    ft.add(R.id.realtabcontent, displayStationInfo); <-- this line causes the error 
    ft.commit(); 
    this.getSupportFragmentManager().executePendingTransactions(); 
} 

singleStationListItem.java здесь

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    Bundle b = this.getArguments(); 

    getActivity().setContentView(R.layout.single_station_item_view); 

    TextView txtStation = (TextView) getActivity().findViewById(R.id.station_label); 

    String station = b.getString("station"); 
    // displaying selected product name 
    Log.d(TAG, "passed in station information: " + station); 
    txtStation.setText(station); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    View v = (LinearLayout)inflater.inflate(R.layout.single_station_item_view, container, false); 
    return v; 
} 

Любая помощь будет gre очень оценили.

ответ

0

Я понимаю, что этот вопрос задан некоторое время назад, я отправляю ответ другим, которые могут столкнуться с этим вопросом.

Насколько я знаю, Android-идентификатор «realtabcontent» отсутствует. В вашем XML удалите «android» часть вашего идентификатора для FrameLayout.

<FrameLayout 
    android:id="@+id/realtabcontent" 
    android:layout_width="fill_parent" 
    android:layout_height="0dp" 
    android:layout_weight="1" /> 

Полный код XML, размещенный на developer documentation выглядит следующим образом:

<android.support.v4.app.FragmentTabHost 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/tabhost" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 

    <TabWidget 
     android:id="@android:id/tabs" 
     android:orientation="horizontal" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="0"/> 

    <FrameLayout 
     android:id="@android:id/tabcontent" 
     android:layout_width="0dp" 
     android:layout_height="0dp" 
     android:layout_weight="0"/> 

    <FrameLayout 
     android:id="@+id/realtabcontent" 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1"/> 

</LinearLayout> 

Удачи и счастливого кодирования!