2011-12-03 59 views
2

我想在我的項目中使用https://github.com/JakeWharton/Android-ViewPagerIndicator插件實現片段。Android片段執行

我的片段

public final class NearByFragment extends Fragment { 
    private static String TAG = "bMobile"; 

    public static NearByFragment newInstance(String content) { 
     NearByFragment fragment = new NearByFragment(); 
     return fragment; 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     Log.d(TAG, "onCreate"); 
     super.onCreate(savedInstanceState); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     Log.d(TAG, "onCreateView"); 
     return inflater.inflate(R.layout.fragment_search_nearby, null); 
    } 
} 

現在我想執行一些代碼就像開始啓動一個新線程,並從服務器下載一個JSON,然後分配從我下載內容的列表視圖。在片段中,我們在onCreateView中分配視圖。所以我應該在哪裏寫

listview = (ListView) findViewById(R.id.list_items); 

((TextView) findViewById(R.id.title_text)) 
       .setText(R.string.description_blocked); 

和其他代碼來生成片段視圖?

回答

3

你可以說你只是誇大視野內搜索:

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     Log.d(TAG, "onCreateView"); 
     View v = inflater.inflate(R.layout.fragment_search_nearby, null); 
     listview = (ListView)v.findViewById(R.id.list_items); 
     ((TextView)v.findViewById(R.id.title_text)) 
         .setText(R.string.description_blocked); 
     return v; 
    } 

你也可以在你的代碼的其他地方使用Fragment.getView()功能,並調用視圖的findViewById()成員。

1

如果您想要訪問佈局元素,可以使用Fragment中的getActivity().findByView()。或者,您可以將findByView()調用放在主Activity中。