如何将数据从一个片段发送到android中的另一个片段?

时间:2015-09-02 02:57:38

标签: android android-layout android-fragments android-activity

enter image description here

您好 我使用寻呼机和片段制作一个简单的标签视图。所以我在视图中有两个选项卡。在一个选项卡中,我有列表视图,其中每行都有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;
    }
}

如上图所示我选择第一站是我最喜欢的站。我需要在第二个标签上显示?可以吗?

3 个答案:

答案 0 :(得分:2)

假设您要将数据从 FragmentA发送到FragmentB ,那么最佳做法是使用接口,然后通过容器活动在片段之间进行通信。下面是一个小片段,它将提供我想说的骨架:

步骤1:在FragmentA中定义一个接口并覆盖onAttach()方法,使容器活动必须实现接口并为其方法提供主体。

UIHintAttribute

现在,在FragmentA中,您可以将值传递给 myMethod(),如:[Display(Name ="Status Name", Prompt ="Type something here!")] [UIHint("PlaceHolder")] public string StatusName { get; set; }

步骤2:现在,在您的容器活动中实现回调接口

    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");
  }
}

步骤3:在FragmentB中有一个方法,例如 methodInFragmentB(yourParameters)

if (listener!=null) {
                        listener.myMethod(yourArguments);
                    }

我希望上面的描述有所帮助。感谢。

答案 1 :(得分:1)

有几种方法可以做到。

最基本和推荐的是在发送Fragment中定义一个接口,然后使容器Activity实现该接口,这样你就可以将数据从Fragment发送到Activity。由此您可以将数据发送到您的接收片段 看一下Google的官方教程:
http://developer.android.com/training/basics/fragments/communicating.html

另一种方法是使用Bus事件样式,它比前一个更酷。您可以使用Otto执行此操作。在您的接收片段中订阅,然后只需从您的发送片段发送您想要的任何数据,无需通信或编写冗长的接口。

答案 2 :(得分:1)

在片段中创建一个界面,并在相应的活动中实现该界面。

您可以参考此链接: https://developer.android.com/training/basics/fragments/communicating.html