2014-11-14 47 views
-1

我有兩個片段,用於我的平板電腦的應用程序的android佈局,並且它們都有Listview。我使用內置的ID android:id="@android:id/list"現在當我試圖在我的活動java文件中引用它們的引用時,我很困惑,我將如何做到這一點。爲android listView @android:id/list創建ID,創建AMBIGUITY


重要的一點:我走在我的活動有引用

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

    setContentView(R.layout.activity_notifications); 
    notificationListView2=(ListView)findViewById(android.R.id.list); //from first fragment 
    notificationListView=(ListView)findViewById(android.R.id.list);//from second fragment 

enter image description here


重要的一點:我走在我的活動有引用

回答

0

在添加的每個片段中將調用onCreateView方法,在給定的方法中,您可以引用片段中的任何對象,也就是說,當您需要存儲對您的ListView項目的引用時。

如果您需要以某種方式從您的活動中訪問您的ListView項目,請創建方法以檢索您在onCreateView方法中分配的變量。因此,在每一個片段

,你將能夠做到以下幾點:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    Log.i("Right", "onCreateView()"); 
    View v = inflater.inflate(R.layout.right, container, false); 
    ListView lv_fragmentXXX = (ListView) view.findViewById(android.R.id.list); //Where xxx is an identifier for each listview in each fragment 
} 
+0

我在我的活動 – nobalG

+0

然後創建一個方法在您的片段中檢索每個ListView,從每個片段,如果它不明確,添加一些代碼來澄清您的問題 – zozelfelfo

+0

好吧似乎是一個乾淨的方法,無論如何增加代碼 – nobalG

1

對於Fragments,onCreateView是你的佈局會膨脹的方法。 此充氣器返回一個View對象,因此請在此視圖對象上調用findViewById(android.R.id.list)

例如。

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_layout_xml, container, false); 
    rootView.findViewById(android.R.id.list); 
    ..... 
    .... any other code .... 
    ..... 
    return rootView; 
} 

這將確保正在訪問正確的列表視圖。