【问题标题】:How to intent string from fragment to another activity如何将字符串从片段意图转移到另一个活动
【发布时间】:2016-10-18 22:44:15
【问题描述】:

我有活动A 和活动B

我有 4 个片段(不是列表片段),其中包含自定义列表视图以及我在活动 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;
}

【问题讨论】:

  • 只是澄清您想将字符串数据从一个活动发送到另一个活动的问题?对吗?
  • 不清楚您在问什么,请准确说明您要达到的目标。
  • 当您单击列表视图中的任何项目时,您需要将字符串传递给活动吗?
  • @jasonlam604 不,我不会尝试将字符串数据发送到另一个活动...我只是希望它传递给另一个活动...
  • @subrahmanyamboyapati 不需要,我只是想让它传递给另一个活动...请帮助伙计...

标签: android android-layout android-fragments android-intent


【解决方案1】:

使用EventBus

快速指南:

将 EventBus 添加到您的项目中 摇篮:

compile 'org.greenrobot:eventbus:3.0.0'

马文:

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

使用事件总线

  1. 定义事件:

    公共静态类 MessageEvent { //你所有的数据发送到这里 字符串 stringToSend; 公共消息事件(字符串 s){ this.stringToSend = s; } }

  2. 准备订阅者:声明和注释您的订阅方法,可选择指定线程模式:

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

注册和注销您的订阅者。例如在 Android 上,Activity 和 Fragment 通常应该根据它们的生命周期进行注册:

@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("你好,这是我的字符串!"));

【讨论】:

  • 我会试试看,谢谢你的建议,如果这对我的代码有效,我会更新..再次感谢
猜你喜欢
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
  • 1970-01-01
相关资源
最近更新 更多