簡體   English   中英

如何將字符串從片段轉移到另一個活動

[英]How to intent string from fragment to another activity

我有活動A和活動B

我有4個片段(不是listfragment),其中包含自定義listview以及我放入活動A圖像和文本。 它是一個TabLayout,可滑動。

如何將字符串從片段轉移到另一個活動?

這是我的片段之一:

public class BusinessSolutionHelperFragment extends Fragment {

    public BusinessSolutionHelperFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    
    }

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

        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.first_fragment_layout, container, false);

        RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
        rv.setHasFixedSize(true);

        MyAdapter adapter = new MyAdapter(new String[]{
                "Sales Promotion Girl (SPG)",
                "Sales Promotion Boy (SPB)",    
        });    

        rv.setAdapter(adapter);    

        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        rv.setLayoutManager(llm); 

        return rootView;
    }

這是我的MainActivity:

public class MenuHelperInsiti extends AppCompatActivity {

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.menu_helper_insiti);

                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
                setSupportActionBar(toolbar);

                // Get the ViewPager and set it's PagerAdapter so that it can display items
                ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
                PagerAdapter pagerAdapter =
                        new PagerAdapter(getSupportFragmentManager(), MenuHelperInsiti.this);
                viewPager.setAdapter(pagerAdapter);

                // Give the TabLayout the ViewPager
                TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
                tabLayout.setupWithViewPager(viewPager);

                // Iterate over all tabs and set the custom view
                for (int i = 0; i < tabLayout.getTabCount(); i++) {
                    TabLayout.Tab tab = tabLayout.getTabAt(i);
                    tab.setCustomView(pagerAdapter.getTabView(i));
                }            
            }            

            @Override
            public void onResume() {
                super.onResume();
            }
            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.menu_main, menu);
                return true;
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                int id = item.getItemId();

                if (id == R.id.action_settings) {
                    return true;
                }

                return super.onOptionsItemSelected(item);
            }

            class PagerAdapter extends FragmentPagerAdapter {

                String tabTitles[] = new String[] {
                        "Home Solution Helper",
                        "Party & Event Helper",
                        "Business Solution Helper",
                        "Professional Helper",
                           };
                Context context;

                public PagerAdapter(FragmentManager fm, Context context) {
                    super(fm);
                    this.context = context;
                }

                @Override
                public int getCount() {
                    return tabTitles.length;
                }

                @Override
                public Fragment getItem(int position) {

                    switch (position) {
                        case 0:
                            return new HomeSolutionHelperFragment();
                        case 1:
                            return new PartyEventHelperFragment();
                        case 2:
                            return new BusinessSolutionHelperFragment();
                        case 3:
                            return new ProfessionalHelperFragment();
                                    }

                    return null;
                }

                @Override
                public CharSequence getPageTitle(int position) {
                    // Generate title based on item position
                    return tabTitles[position];
                }

                public View getTabView(int position) {
                    View tab = LayoutInflater.from(MenuHelperInsiti.this).inflate(R.layout.custom_tab, null);
                    TextView tv = (TextView) tab.findViewById(R.id.custom_text);
                    tv.setText(tabTitles[position]);
                    return tab;
                }            
            }   

這是我的first_fragment_layout

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </android.support.v7.widget.RecyclerView>
</RelativeLayout>

這是我的tab_layout:

    <RelativeLayout
    android:id="@+id/main_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MenuHelperInsiti">    

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        />

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_below="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        app:tabTextColor="#d3d3d3"
        app:tabSelectedTextColor="#ffffff"
        app:tabIndicatorColor="#ff00ff"
        android:minHeight="?attr/actionBarSize"
        app:tabGravity="fill"
        app:tabMode="scrollable"

                                />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_below="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</RelativeLayout>

這是適配器:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDataset;

// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
    public CardView mCardView;
    public TextView mTextView;
    public MyViewHolder(View v) {
        super(v);

        mCardView = (CardView) v.findViewById(R.id.card_view);
        mTextView = (TextView) v.findViewById(R.id.tv_text);
    }
}

// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
    mDataset = myDataset;
}

// Create new views (invoked by the layout manager)
@Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                                 int viewType) {
    // create a new view
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_item, parent, false);

    // set the view's size, margins, paddings and layout parameters
    MyViewHolder vh = new MyViewHolder(v);
    return vh;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    holder.mTextView.setText(mDataset[position]);
}

@Override
public int getItemCount() {
    return mDataset.length;
}

使用EventBus

快速指南:

將EventBus添加到您的項目Gradle:

compile 'org.greenrobot:eventbus:3.0.0'

Maven:

<dependency>
    <groupId>org.greenrobot</groupId>
    <artifactId>eventbus</artifactId>
    <version>3.0.0</version>
</dependency>

使用eventBus

  1. 定義事件:

    公共靜態類MessageEvent {//所有要在此處發送的數據String StringToSend; 公共MessageEvent(String s){this.stringToSend = s; }}

  2. 准備訂閱者:聲明並注釋您的訂閱方法,可以選擇指定線程模式:

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event){/ *做某事* /};

注冊和注銷您的訂戶。 例如,在Android上,活動和片段通常應根據其生命周期進行注冊:

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}
  1. 發布事件(在您要發送數據的地方使用)

    EventBus.getDefault()。post(new MessageEvent(“你好,這是我的String!”));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM