当前位置: 首页 > 知识库问答 >
问题:

如何在活动和取景器片段之间传递值?[重复]

钱宇
2023-03-14

这可能是一个愚蠢的问题,但我正在努力解决如何在activity和viewpager之间传递值的问题。现在让我解释一下我的要求,我有两个标签,即任务和调用。当用户按下任务中的一个按钮,它将从中转到新活动时,将有两种形式:一种是edittext,另一种是spinner,需要从该活动数据在任务片段中填充listview。到目前为止,我尝试的是:

这是我的主要活动:

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

        }
    }

这是我的任务片段(在这里填充listview)

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

    }

这是数据填充任务片段中listview的活动:

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();

            }
        });
    }
}

在这里,如何在活动和viewpager片段之间传递数据,有人能帮我吗?提前谢谢!

共有2个答案

水睿
2023-03-14

您应该在片段中创建一个NewInstance方法。简而言之,它可能是这样的:

public class MyFragment {
    private int value;

    private static final String ARG_VALUE = "argValue";

    public static MyFragment NewInstance(int value) {
        Bundle args = new Bundle();
        args.putInt(ARG_VALUE, value);

        MyFragment fragment = new MyFragment();
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate() {
        Bundle args = getArguments();
        this.value = args.getInt(ARG_VALUE, 0); // Default 0 if key not found.
    }
}

只要在创建片段时传入该值:

MyFragment tenFragment = MyFragment.newInstance(10);

然后,它可以在片段事务中使用,也可以插入到FragmentStatePagerAdapter中,但您需要它。同样的原则也适用于任何数据类型,因此如果需要传入字符串或您自己的可序列化对象等,您可以这样做。

蒲昊苍
2023-03-14

您可以使用捆绑数据活动传递到片段

活动中,创建您的捆绑包,并将其添加到片段

Bundle myBundle = new Bundle();
myBundle .putLong( "exampleId", mExampleId);
myBundle .putString("exampleName", mName);
...
myFragment.setArguments( myBundle  );

然后,当创建片段时,使用函数getArguments()获取包中的值,如:

Long exampleId = getArguments().getLong("exampleId");

甚至设置默认值,如果你没有在你的Bundle中找到密钥

String exampleName = getArguments().getString( "exampleName", "None"));

 类似资料:
  • 如何从secondactivity.java中的包到fragment_2.java文件中获取值?

  • 当我关闭一个活动时,我希望它将一个值传递给另一个活动中的一个片段,我该怎么做? 活动B 片段A 代码不起作用,因为它给了我一个错误 谢啦

  • 如何从片段和活动中传递和获取值?

  • 我有两项活动。两者都已实现surfaceview。在第一个活动中,我有一个名为score1的变量,我想将score1中的值传递给第二个活动。 每次我运行应用程序时,它在完成第一个活动后崩溃,并尝试加载第二个活动。在我编写代码以获取第二个活动中的额外意图之前,一切都很好。 我的第一个活动有这样的意图: 在我的第二个活动中,以下代码试图获取score1变量的值: 我不明白为什么每次activity o

  • 我在片段和活动之间的导航遇到了麻烦,我使用了Android Studios2.2.3的自动生成模板,并自定义了它来在片段之间导航。 我添加了五个片段,并在导航抽屉活动中使用片段来使用本教程。

  • 我正在开发一个由多个活动组成的Android应用程序,我必须在它们之间传递ab对象,但我不能通过使用意图传递它,因为对象的类没有实现可序列化,我怎么做?我无法修改我的类的源代码。谢谢:)