2013-03-08 16 views
2

在我的應用程序中,我有一個活動,在操作欄選項卡導航模式中有兩個片段,就像android開發人員網站示例一樣。Fragment的ListView項中的按鈕接口定義?

在我的第一個片段中我有一個listview(它有自己的適配器),listview的每個項目都有一個名爲+1的按鈕。我想要刷新第二個片段,它顯示第一個片段中listview中的項目,它們的+1按鈕被點擊。我知道我不得不使用接口。但我不知道如何使用它們。我必須在哪裏定義界面?如何使用它?以及如何從活動中訪問它以刷新第二個片段?

快速的幫助將是偉大的。謝謝。

+0

您是否想要點擊「每個listItem內的按鈕」導航到第二個片段,或者使用界面單擊每個listItem? – SKK 2013-03-08 14:13:07

+0

@Santhosh不,我想添加項目的按鈕點擊(從第一個片段)以顯示在第二個片段的列表視圖中(通過刷新第二個片段,數據在一個文件中暫存)。這意味着我必須在第一個片段中的listview項目按鈕與包含這兩個片段的活動之間進行通信。 – 2013-03-08 14:28:09

回答

4

如果你想讓它在列表項點擊

片段A:

public class FragmentA extends ListFragment { 

OnItemSelectedListener mListener; 

... 
// Container Activity must implement this interface 
public interface OnItemSelectedListener { 
    public void onItemSelected(int position); 
} 
... 

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 
    try { 
     mListener = (OnItemSelectedListener) activity; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(activity.toString() + " must implement OnItemSelectedListener"); 
    } 
} 

@Override 
public void onListItemClick(ListView l, View v, int position, long id) { 

    mCallback.onItemSelected(position); 

    } 
} 

ContainerActivity:

public class ContainerActivity extends FragmentActivity 
    implements FragmentA.OnItemSelectedListener 
{ 

//... 



public void onItemSelected(int Position/*pass anything which u want*/) 
    { 

     SecondFragment second_fragment = (SecondFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentB); 

     if(second_fragment !=null) 
     { 
      second_fragment.UpdateUI(Position); 
     } 

    } 


} 

第二塊碎片:

public class SecondFragment extends Fragment { 

    ... 
    public void UpdateUI(Position) 
    { 

    } 

} 

希望這有助於。點擊每個listitem中的按鈕可能有點困難,但嘗試相同的方法。也許你必須編寫接口聲明並調用你的自定義適配器。

+0

我會測試一下。但我必須添加這個,點擊的按鈕是在列表視圖item.so接口聲明必須在片段範圍內或列表視圖範圍的適配器?謝謝 – 2013-03-08 14:38:23

+0

是的,這是我的想法和建議。但是,我不能肯定地說它會起作用,因爲我沒有處理過這樣的要求。 – SKK 2013-03-08 14:41:56

+0

這是什麼:在列表視圖適配器中聲明接口 - >在託管活動中調用它 - >從那裏調用片段中的另一個方法?我對嗎? – 2013-03-08 21:50:12

相關問題