如何将值从其他活动传递给 viewpager 片段?

Posted

技术标签:

【中文标题】如何将值从其他活动传递给 viewpager 片段?【英文标题】:How to pass value to viewpager fragment from other activity? 【发布时间】:2016-04-24 11:13:09 【问题描述】:

在这里让我解释一下我的要求,我有两个 viewpager 选项卡,即任务和调用。任务片段中有一个按钮,当用户单击它将从那里转到新活动时,用户将在edittext中输入值,然后来自该活动的值需要在该viewpager的任务片段中填充列表视图我该怎么做。到目前为止,我尝试过的是:

这是我的主要活动:

package servicefiirst.precision.activitiestabs;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity 

    /**
     * The @link android.support.v4.view.PagerAdapter that will provide
     * fragments for each of the sections. We use a
     * @link FragmentPagerAdapter derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * @link android.support.v4.app.FragmentStatePagerAdapter.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The @link ViewPager that will host the section contents.
     */
    private ViewPager mViewPager;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        //  Bundle bundle=getIntent().getExtras();
        // Intent intent=getIntent();
        //   ActivityView activityView=(ActivityView)intent.getSerializableExtra("yog");
        //     intent.putExtra("yogs",activityView);
        // Bundle bundle=new Bundle();
        // bundle.putSerializable("yogs",activityView);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) 
            String yogan = bundle.getString("yog");
            String yogans = bundle.getString("yogs");
            Bundle bundle1 = new Bundle();
            bundle.putString("yoges", yogan);
            bundle.putString("yogesh", yogans);
            Task task = new Task();
            task.setArguments(bundle1);


        
    

    @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) 
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) 
            return true;
        

        return super.onOptionsItemSelected(item);
    

    /**
     * A placeholder fragment containing a simple view.
     */


    /**
     * A @link FragmentPagerAdapter that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter 

        public SectionsPagerAdapter(FragmentManager fm) 
            super(fm);
        

        @Override
        public Fragment getItem(int position) 
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
                switch (position)
                    case 0:
                            Task task=new Task();
                            return task;

                    case 1:
                            Calls calls=new Calls();
                            return calls;

                
        return null;
        

        @Override
        public int getCount() 
            // Show 3 total pages.
            return 2;
        

        @Override
        public CharSequence getPageTitle(int position) 
           switch (position)
               case 0:
                   return "Task";
               case 1:
                   return "Call";

            
        return null;
            

        
    

这是 viewpager 中的任务片段,其中 listview 在那里:

package servicefiirst.precision.activitiestabs;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;
public class Task extends Fragment

    List<ActivityView>activityViews;
    ActivityView activityView=new ActivityView();
    ActivityListAdapter activityListAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 

        View rootview= inflater.inflate(R.layout.yog,container,false);
        ListView listview=(ListView)rootview.findViewById(R.id.listView);
        if (activityViews == null)
        
            activityViews = new ArrayList<ActivityView>();

        
        if(getArguments()!=null) 
            getArguments().getSerializable("yog");
        
        activityViews.add(activityView);
            activityListAdapter = new ActivityListAdapter(getActivity(), R.id.listView, activityViews);
            listview.setAdapter(activityListAdapter);
            activityListAdapter.notifyDataSetChanged();
            Button btn=(Button)rootview.findViewById(R.id.button2);
            btn.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v)
            
                Intent intent = new Intent(getActivity(), DetailActivity.class);
                startActivity(intent);
            
        );



        return rootview;
    

    

这是数据在任务片段中填充列表视图的详细活动:

package servicefiirst.precision.activitiestabs;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class DetailActivity extends AppCompatActivity 
    ActivityView activityView = new ActivityView();
    // public static String endpoint;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        final EditText editText = (EditText) findViewById(R.id.editText);
        final Spinner spinner = (Spinner) findViewById(R.id.spinner);
        final ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.yog, R.layout.support_simple_spinner_dropdown_item);
        spinner.setAdapter(arrayAdapter);
        final Button btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                activityView.setDescription(editText.getText().toString());
                activityView.setStatus(spinner.getSelectedItem().toString());
              //  Bundle bundle=new Bundle();
               // bundle.putSerializable("yog", activityView);
                Task task=new Task();
                //task.setArguments(bundle);
                android.support.v4.app. FragmentManager fm=getSupportFragmentManager();
                android.support.v4.app.  FragmentTransaction ft=fm.beginTransaction();
                ft.add(R.id.container,task,"");
                ft.commit();

            
        );
    

如何将数据从其他活动导航到其他活动的浏览器片段?谁能帮帮我

【问题讨论】:

使用 startActivityForResult() 方法启动活动。您可以在 taskfragment 中使用 onActivityResult() 方法从 Activity 中检索数据。 你能详细解释一下吗@Sudheer 【参考方案1】:

请使用静态变量从您的活动中保存值,然后通过调用 viewpager 活动的任务片段在任务片段中重新使用它,我想它会对您有所帮助..!!

【讨论】:

在我的情况下是传递对象 在这种情况下,您可以改为接口回调 你能分享一些sn-p吗【参考方案2】:

使用

从任务片段启动活动
startActivityForResult(Intent intent, int requestCode)

方法,它会让fragment从activity接收结果数据。在按下按钮填充值的新活动中,将值保存到意图,以便您可以使用

将该意图发送到片段
setResult(intent) // setResult has other overloaded methods pick them to your requirement

按钮onClickListener onClick()方法中Activity类的方法。

    Ex : onClick() 
        intent.putString("name", editText.getText());
        setResult(intent); // setting the intent as result to receive at fragment
        this.finish(); // To finish the activity
 

当活动完成时(当你调用finish() 或按下返回按钮时)

onActivityResult(intent)

启动activity的Fragment方法会被自动调用。您可以使用此方法检索包含填充数据的意图。

【讨论】:

以上是关于如何将值从其他活动传递给 viewpager 片段?的主要内容,如果未能解决你的问题,请参考以下文章

如何将值从一个活动中的片段传递到另一个活动? [复制]

在 Kotlin 中将值从 Activity 传递到 Fragment

如何将值从动态列表视图传递到活动?

如何将值从一个片段的回收器视图项传递到另一个片段

如何将值从活动传递到 Android Studio 中的类?

如何将值从基本适配器传递到 Android 中的 Activity