2011-07-22 38 views
3

我正在編寫我的第一個帶有碎片的android應用程序,這裏是我的問題。我有主要活動和3個片段。所有3個片段是相同的類別,因此所有3個片段具有相同的佈局。但我需要每個片段在該佈局中具有不同的標題。但是我無法選擇我需要的TextView,因爲所有這些碎片TextViews由於相同的佈局而具有相同的ID。有沒有一些簡單的方法來做到這一點。同一個片段在一個活動問題

感謝名單

回答

4

鑑於你的碎片f1f2f3,你可以嘗試f1.getView().findViewById(id)f2.getView().findViewById(id)f3.getView().findViewById(id)的搜索範圍內的每個時間減少到只有特定的片段。

但是,我認爲使用Fragments的目的是爲了提高模塊性並避免將所有視圖暴露給Activity。它可以由片段控制。您可以在片段內部解析視圖,然後在片段上爲活動提供一個setTitle()方法。

+0

哦...這很容易..對不起,這麼蹩腳的問題,謝謝 – Semanticer

1

的ID不應該的問題,因爲每個類將被誇大了自己的佈局實例。嘗試使用相同的ID。

+0

但我不知道如何通過getActivity()來訪問這個TextView。findViewById(R.id.agenda_title); – Semanticer

+0

使用fragment.getView()。findViewById(R.id.agenda_title) –

-1

如果在'fragment'下你的意思是一個UI組件,你應該爲你的佈局中的每個組件指定不同的ID!

<LinearLayout 
    android:id="@+id/LinearLayout" 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 

    <TextView 
     android:id="@+id/header" 
     android:layout_width="fill_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1" 
     android:background="#ff0000" 
     android:text="Header" 
     /> 

    <TextView 
     android:id="@+id/body" 
     android:layout_width="fill_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1" 
     android:background="#00ff00" 
     android:text="Body" 
     /> 

    <TextView 
     android:id="@+id/footer" 
     android:layout_width="fill_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1" 
     android:background="#0000ff" 
     android:text="Footer" 
     /> 

</LinearLayout> 

如果你指的是主XML佈局內的其他XML片段,您可以用相同的ID,但在不同的XML片段!

相關問題