将数据从活动传递到片段 [英] Passing data from Activity to Fragments

查看:64
本文介绍了将数据从活动传递到片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经完成了一个简单的应用程序,可以通过json列出mysql数据库中的所有产品.单击特定产品时,它将带我到显示其详细信息的活动.现在,我更改了我的应用程序,以便当我从列表中单击特定产品时,它会转到3个选项卡式片段.我已经创建了所有相关的片段,并且一切正常.仅当我尝试将所有产品列表活动中的数据传递到明细片段活动中时,它才行不通.如何将列出所有产品的主屏幕中的数据传递到显示详细信息的3个片段中?

I have finished a simple app to list all products from a mysql database via json. When I click a specific product, it takes me to an activity that displays it's details. Now I changed my app so that when I click a specific product from the list it goes to a 3 tabbed fragment. I have created all the relevant fragments and everything works fine. It only doesn't work when I try to pass the data from the list all products activity to the details fragment activity. How can I pass the data from the main screen which lists all products to the 3 fragments that display the details?

进一步的解释:

没有框架的工作示例:主活动显示所有产品,并在选择单个产品时将其传递给详细活动->详细活动从主活动获取数据并显示详细信息

working example without the framents: Main activity displays all products and passes it to details activity upon selecting a single product-> details activity gets data from main activity and displays details

现在,我的主要活动是显示所有产品.我应该将数据传递到->公共类EmpresaDetailsActivity扩展FragmentActivity实现ActionBar.TabListener {等"还是必须将其传递给我创建的所有其他3个单个片段?

Now I have the main activity which displays all products. Do I pass the data to -> "public class EmpresaDetailsActivity extends FragmentActivity implements ActionBar.TabListener { etc" or do I have to pass it to all other 3 single fragments that I created?

(旧方法)列出所有产品:

(old way)List all products:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_empresas);

        empresaList = new ArrayList<HashMap<String, String>>();

        // Get listview
        ListView lv = getListView();

        // on selecting single empresa
        // launching Empresa Details Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // getting values from selected ListItem
                String eid = ((TextView) view.findViewById(R.id.eid)).getText().toString();
                String marca = ((TextView) view.findViewById(R.id.marca)).getText().toString();
                String investimento = ((TextView) view.findViewById(R.id.investimento)).getText().toString();
                String marcatotal = ((TextView) view.findViewById(R.id.marcatotal)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),EmpresaDetailsActivity.class);
                // sending data to next activity
                in.putExtra(TAG_EID, eid);
                in.putExtra(TAG_MARCA, marca);
                in.putExtra(TAG_INVESTIMENTO, investimento);
                in.putExtra(TAG_MARCATOTAL, marcatotal);

                // starting new activity and expecting some response back
                startActivity(in);
            }
        });

        // Loading empresa in Background Thread
        new LoadAllEmpresa().execute();
    }

(旧方法)单个产品的详细信息:

(old way)Details of a single product:

public class EmpresaDetailsActivity  extends Activity {

    // JSON node keys
    private static final String TAG_EID = "eid";
    private static final String TAG_MARCA = "marca";
    private static final String TAG_INVESTIMENTO = "investimento";
    private static final String TAG_MARCATOTAL = "marcatotal";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details_empresa);

        // getting intent data
        Intent in = getIntent();

        // Get JSON values from previous intent
        String eid = in.getStringExtra(TAG_EID);
        String marca = in.getStringExtra(TAG_MARCA);
        String investimento = in.getStringExtra(TAG_INVESTIMENTO);
        String marcatotal = in.getStringExtra(TAG_MARCATOTAL);

        // Displaying all values on the screen
        TextView lblEid = (TextView) findViewById(R.id.showEid);
        TextView lblName = (TextView) findViewById(R.id.showMarca);
        TextView lblInvestimento = (TextView) findViewById(R.id.showInvestimento);
        TextView lblMarcatotal = (TextView) findViewById(R.id.showMarcaTotal);

        lblEid.setText(eid);
        lblName.setText(marca);
        lblInvestimento.setText(investimento);
        lblMarcatotal.setText(marcatotal);
    }
}

具有3个片段的New Details类:

New Details class that has the 3 fragments:

public class EmpresaDetailsActivity extends FragmentActivity implements ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "Apresentação", "Ficha Técnica", "Pedir Informação" };

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

        // Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }

}

TabsPagerAdapter类:

TabsPagerAdapter class:

public class TabsPagerAdapter extends FragmentPagerAdapter {

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {

        switch (index) {
        case 0:
            // Top Rated fragment activity
            return new ApresentacaoFragment();
        case 1:
            // Games fragment activity
            return new FichaTecnicaFragment();
        case 2:
            // Movies fragment activity
            return new PedirInformacaoFragment();
        }

        return null;
    }

    @Override
    public int getCount() {
        // get item count - equal to number of tabs
        return 3;
    }

}

3个片段之一的示例:

example of 1 of the 3 fragments:

public class ApresentacaoFragment extends Fragment {

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

        View rootView = inflater.inflate(R.layout.fragment_apresentacao, container, false);

        return rootView;
    }
}

在启动片段之前,

推荐答案

在活动onItemClick()上:

On your activity onItemClick(), before launching the fragment:

Bundle args = new Bundle();
args.putString(TAG_EID, eid);
args.putString(TAG_MARCA, marca);
args.putString(TAG_INVESTIMENTO, invetstimento);
args.putString(TAG_MARCATOTLA, marcatotal);
yourFragment.setArguments(args);

在片段上OnCreateView():

On your fragment OnCreateView():

Bundle args = getArguments();
String marca = args.getString(TAG_MARCA);
// and so on...

更清楚地说,这是如何在活动/片段"之间传递数据.

And to be more clear, here is how you should pass data between Activities/Fragments.

  • 活动->片段:使用Bundle和setArguments.(如上所示)
  • 活动->活动:使用Intent和putExtra.
  • 片段->活动:使用界面.主动性应该实现它,片段应该调用它.

检查新代码后:

  1. 将您的字符串包装在包中,并将其从MainActivity传递到EmpresaDetailsActivity.
  2. 使用getIntent().getExtras()在此处获取它.
  3. 将TabsPagerAdapter更改为:

  1. Wrap your Strings inside a Bundle and pass it from MainActivity to your EmpresaDetailsActivity.
  2. Fetch it there using getIntent().getExtras().
  3. Change your TabsPagerAdapter to:

public class TabsPagerAdapter extends FragmentPagerAdapter {

private Bundle args;

public TabsPagerAdapter(FragmentManager fm, Bundle args) {
    super(fm);
    this.args = args;
}

@Override
public Fragment getItem(int index) {

switch (index) {
case 0:
    // Top Rated fragment activity
    ApresentacaoFragment apresentacaoFragment = new ApresentacaoFragment();
    apresentacaoFragment.setArguments(args);
    return apresentacaoFragment;
case 1:
    // Games fragment activity
    // do the same as above with your Games fragmnet class
case 2:
    // Movies fragment activity
    // ...
}

return null;
 }

 @Override
public int getCount() {
    // get item count - equal to number of tabs
    return 3;
}   
}

  1. 实例化适配器时,将包传递给其构造函数.
  2. 在您的片段类中,使用getArguments()来获取捆绑包,您就完成了.

这篇关于将数据从活动传递到片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆