2013-07-01 66 views
0

我是新來的片段,並一直在試圖解決這個好幾天。我想有我片段在列表視圖點擊更新,並且極其類似: Fragment in fragment do not refresh 那裏既是左邊列表視圖和右側的標籤UI。這是我的一個片段:刷新上ListView項片段點擊

public static class DescriptionFragment extends Fragment { 

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


     View rootView = inflater.inflate(R.layout.fragment_section_description, container, false); 

     text = ((TextView) rootView.findViewById(R.id.description)); 

     text.setText(Html.fromHtml(description_text)); 


     return rootView; 
    } 

我怎麼能叫這個片段(從主要活動中),所以onCreateView被更新和TextView的「文本」更新?任何幫助是極大的讚賞

注:列表視圖不是一個片段,只是平板電腦一個單獨的佈局文件。我唯一的片段(如DescriptionFragment)是標籤

+0

http://android-er.blogspot.in/2011/12/access-view-inside-fragment-from.html。可能會幫助 – Raghunandan

回答

0

我假設你綁顯示列表視圖和列表項的點擊,值應該是更新:

我怎樣才能把這個fragement(從內主要活動)所以onCreateView被更新並且textview的'text'被更新了?

要調用的主要活動中的片段,你必須定義側的主XML文件片段象下面這樣:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="horizontal" > 
<fragment 
android:id="@+id/frag_series" 
android:layout_width="200dip" 
android:layout_height="match_parent" 
android:layout_marginTop="?android:attr/actionBarSize" 
class="com.example.demo_fragment.MyListFragment" /> 
</LinearLayout> 

現在擴展Listframent而不是和代碼來填充的ListView數據後火單擊事件像下面

@Override 
public void onListItemClick(ListView l, View v, int position, long id) { 
String item = (String) getListAdapter().getItem(position); 
DetailFragment frag = (DetailFragment) getFragmentManager().findFragmentById(R.id.frag_capt); 
if (frag != null && frag.isInLayout()) { 
frag.setText(getCapt(item)); 
} 
} 

,然後檢查條件和更新vaules,如下圖所示:

private String getCapt(String ship) { 
if (ship.toLowerCase().contains("android")) { 
return "Andy Rubin"; 
} 
if (ship.toLowerCase().contains("IOS")) { 
return "Steve Jobs"; 
} 
return "???"; 
} 
+0

感謝您的幫助。我已經把片段在我的XML文件,但是這在我的列表視圖: 「DescriptionFragment FRAG =(DescriptionFragment)getFragmentManager()findFragmentById(R.id.frag_description);」給我錯誤無法從片段投射到kick_activity.DescriptionFragment –

0

這是您可以調用片段的方式。

DescriptionFragment descriptionFragment = (DescriptionFragment) 
getFragmentManager().findFragmentById(R.id.yourFragmentId); 
0

你必須創建一個偵聽Interface像這樣

public interface FragmentTransactionListener { 
    public void updateFragment(/*some attributes*/); 
} 

然後,您必須實現您Fragment接口並重寫updateFragment方法。在這種方法中,您可以添加您的代碼,當您的列表項被點擊時,將在Fragment中執行。事情是這樣的

public static class DescriptionFragment extends Fragment implements FragmentTransactionListener { 

... 

    @Override 
    public void updateFragment(/*some attributes*/) { 
     //do some stuff 
    } 

... 

當創建您的片段你FragmentActivity得到這個監聽器的實例,並調用它被點擊列表項時。同樣的事情也該代碼

FragmentTransactionListener listener = instance of your fragment; 

//in your list item you then call this 
listener.updateFragment(/*some attributes*/); 

希望這有助於