2015-09-02 134 views
1

enter image description here如何從一個片段發送數據到另一個片段中的Android?

你好 我用pager和fragment做了一個簡單的tab選項。所以,我有兩個選項卡在我看來。在一個選項卡我有,其中每行有TextView的和喜愛的圖像按鈕列表視圖。第二標籤,我需要顯示所有項目的名稱就是最喜歡在第一個選項卡。所以我需要發送從一個片段列表到另一個列表。

這裏是我的代碼

Mainactivity.java

public class MainActivity extends FragmentActivity implements ActionBar.TabListener { 
    ViewPager viewPager; 
    FragmentpagerAdapter fragmentpagerAdapter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     final ActionBar actionBar =getActionBar(); 
     viewPager = (ViewPager) findViewById(R.id.pager); 
     fragmentpagerAdapter =new FragmentpagerAdapter(getSupportFragmentManager()); 
     viewPager.setAdapter(fragmentpagerAdapter); 
     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 
     actionBar.addTab(actionBar.newTab().setText("Stations").setTabListener(this)); 
     actionBar.addTab(actionBar.newTab().setText("fav Station").setTabListener(this)); 

     viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { 
      @Override 
      public void onPageScrolled(int i, float v, int i1) { 

      } 

      @Override 
      public void onPageSelected(int i) { 
      actionBar.setSelectedNavigationItem(i); 
      } 

      @Override 
      public void onPageScrollStateChanged(int i) { 

      } 
     }); 

    } 


    @Override 
    public void onTabSelected(ActionBar.Tab tab, android.app.FragmentTransaction ft) { 

     viewPager.setCurrentItem(tab.getPosition()); 

    } 

    @Override 
    public void onTabUnselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) { 

    } 

    @Override 
    public void onTabReselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) { 

    } 
} 

activity_main.xml中

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/pager" 
    > 


</android.support.v4.view.ViewPager> 

fragmentone.java

public class Fragmentone extends Fragment{ 

    ArrayList<DataModel> name; 
    boolean isPressed=false; 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_one, container, false); 
     name=new ArrayList<DataModel>(); 
     name.add(new DataModel("First Station",false)); 
     name.add(new DataModel("Second Station",false)); 





     ListView listView = (ListView) view.findViewById(R.id.list_view); 

     CustomAdapter customAdapter =new CustomAdapter(getActivity(),name); 
     listView.setAdapter(customAdapter); 



     return view; 
    } 


} 

customAdapter.java

public class CustomAdapter extends BaseAdapter implements View.OnClickListener { 

    private Activity activity; 
    private ArrayList data; 
    private static LayoutInflater inflater = null; 
    boolean isPressed=false; 


    public CustomAdapter(Activity a, ArrayList d) { 

     /********** Take passed values **********/ 
     activity = a; 
     data = d; 
     inflater = (LayoutInflater) activity. 
       getSystemService(Context.LAYOUT_INFLATER_SERVICE); 


    } 


    @Override 
    public int getCount() { 
     if (data.size() <= 0) 
      return 1; 
     return data.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return position; 
    } 

    @Override 
    public void onClick(View v) { 



    } 

    /********* 
    * Create a holder Class to contain inflated xml file elements 
    *********/ 
    public static class ViewHolder { 

     public TextView text; 

     public ImageButton imageButton; 

    } 

    @Override 
    public long getItemId(int position) { 
     return 0; 
    } 

    @Override 
    public View getView(final int position, View convertView, ViewGroup parent) { 

     View vi = convertView; 
     final ViewHolder holder; 

     if (convertView == null) { 

      /****** Inflate tabitem.xml file for each row (Defined below) *******/ 
      vi = inflater.inflate(R.layout.row_layout, null); 

      /****** View Holder Object to contain tabitem.xml file elements ******/ 

      holder = new ViewHolder(); 
      holder.text = (TextView) vi.findViewById(R.id.station_name); 

      holder.imageButton = (ImageButton) vi.findViewById(R.id.favorite); 
      holder.imageButton.setBackgroundResource(R.drawable.off); 

      /************ Set holder with LayoutInflater ************/ 
      vi.setTag(holder); 
     } else 
      holder = (ViewHolder) vi.getTag(); 

     if (data.size() <= 0) { 
      holder.text.setText("No Data"); 

     } else { 

      DataModel dataModel = (DataModel) data.get(position); 

      /************ Set Model values in Holder elements ***********/ 

      holder.text.setText(dataModel.getText()); 

      // this is for overall row click 
      vi.setOnClickListener(new View.OnClickListener() { 



       @Override 
       public void onClick(View v) { 
        Log.d("row is click","row click"+position); 
       } 
      }); 
      // this is for image button onclick 
      holder.imageButton.setOnClickListener(new View.OnClickListener() { 
       DataModel dataModel = (DataModel) data.get(position); 
       @Override 
       public void onClick(View v) { 
        if(dataModel.isselected()){ 
         holder.imageButton.setBackgroundResource(R.drawable.off); 
         dataModel.setIsselected(false); 
        }else{ 
         holder.imageButton.setBackgroundResource(R.drawable.on); 
         dataModel.setIsselected(true); 
        } 
        isPressed = !isPressed; // reverse 

       } 
      }); 
      ; 


     } 
     return vi; 
    } 
} 

datamodel.java

public class DataModel { 

    String text; 

    DataModel(String text, boolean isselected) { 
     this.text = text; 
     this.isselected = isselected; 
    } 

    public String getText() { 
     return text; 
    } 

    public void setText(String text) { 
     this.text = text; 
    } 

    public boolean isselected() { 
     return isselected; 
    } 

    public void setIsselected(boolean isselected) { 
     this.isselected = isselected; 
    } 

    boolean isselected; 
} 

fragmentone.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:background="#325633" 
    > 

    <ListView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/list_view"> 
    </ListView> 

</LinearLayout> 

rowlayout.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal" 
    android:descendantFocusability="blocksDescendants"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/station_name" 
     android:padding="10dp" 
     android:textColor="#eee345" 
     android:textAppearance="?android:textAppearanceLarge" 
     /> 

    <ImageButton android:id="@+id/favorite" 
     android:layout_width="wrap_content" 
     android:layout_height="fill_parent" 

     android:background="#00ffffff" 
    /> 


</LinearLayout> 

fragmenttwo.java

public class FragmentTwo extends Fragment { 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.fragment_two, container, false); 
    } 
} 

fragmenttwo.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:background="#ee2333"> 

</LinearLayout> 

enter image description here

public class FragmentpagerAdapter extends FragmentPagerAdapter { 


    public FragmentpagerAdapter(FragmentManager fm) { 
     super(fm); 
    } 

    @Override 
    public Fragment getItem(int i) { 

     switch (i) { 

      case 0: 
       return new Fragmentone(); 
      case 1: 
       return new FragmentTwo(); 
      default: 
       break; 



     } 
     return null; 
    } 

    @Override 
    public int getCount() { 
     return 2; 
    } 
} 

如圖像中顯示上述我選擇第一站是我喜歡的電臺。我需要顯示第二標籤上?可以嗎?

+0

您需要將您的FragmentpagerAdapter添加到您的文章 –

+0

確定我會張貼.. !! – user944513

+0

一種解決方案可能是創建一個全局靜態varibale和函數,您可以將數據保存到其他片段中,然後使用第一個片段的靜態方法使用該靜態varibale。 – RajSharma

回答

1

有幾個方式做到這一點。

最基本,最推薦的一個是在你發送片段定義一個接口,然後使容器活動實現這個接口,所以你可以從你的片段活動發送數據。從那裏你可以發送數據到你的接收片段。
看看這個官方教程從谷歌:
http://developer.android.com/training/basics/fragments/communicating.html

另一種方法是使用公交車事件的風格,這比前一個更涼爽。您可以使用Otto這樣做。在收到的Fragment中訂閱,然後發送您想要從發送的Fragment中獲取的任何數據,無需進行通信或寫入冗長的接口。

2

假設您要將數據從FragmentA發送到FragmentB,那麼最佳做法是使用接口,然後通過容器活動在片段之間進行通信。下面是一個小片段,將與我所想說的骨架提供:

第1步:在你FragmentA定義一個接口,並覆蓋onAttach()方法來強制要求你的容器活動實現接口併爲其方法提供主體。現在

public interface MyInterfaceListener{ 
     public void myMethod(yourParameters)//this method will hold parameters which you can then use in your container activity to send it to FragmentB 
} 

private MyInterfaceListener listener; 
@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 
    if (activity instanceof MyInterfaceListener) { 
    listener = (MyInterfaceListener) activity;// This makes sure that the container activity has implemented 
    // the callback interface. If not, it throws an exception 
    } else { 
    throw new ClassCastException(activity.toString() 
     + " must implemenet MyListFragment.OnItemSelectedListener"); 
    } 
} 

,在你FragmentA可以傳遞價值myMethod的(),如:if (listener!=null) { listener.myMethod(yourArguments); }

步驟2:現在,在容器中的活動實現回調接口

public class MyActivity extends Activity implements MyInterfaceListener{ 
     @Override 
     public void myMethod(yourParameters) { 
       //do your stuff here. do whatever you want to do with the //parameter list which is nothing but data from FragmentA. 
       FragmentB fragment = (FragmentB) getSupportFragmentManager().findFragmentById(R.id.yourFragmentB); 
       fragment.methodInFragmentB(sendDataAsArguments);// calling a method in FragmentB and and sending data as arguments. 
     } 
} 

第3步:在FragmentB有一個方法說例如methodInFragmentB(yourParameters )

public void methodInFragmentB(yourParameters){ 
     //do whatever you want to do with the data..... 
} 

我希望上面的描述有幫助。謝謝。

+0

感謝您的回答我會盡快給您更新.. – user944513

相關問題