【问题标题】:Can I replace fragment layout outside of the fragment activity我可以在片段活动之外替换片段布局吗
【发布时间】:2020-01-26 05:29:48
【问题描述】:

我正在开发应用程序,当我点击菜单按钮收藏夹列表打开时出现问题,但我想从主要活动中访问它,可能像这样在图像中:

【问题讨论】:

  • 您的意思是要从主列表中打开收藏列表吗?
  • 是的先生,这就是我想要的

标签: android android-layout android-fragments sharedpreferences


【解决方案1】:

如果您想从列表移动到项目详细信息,您可以在 RecyclerView 的适配器中传递您的数据。

  @Override
    public void onBindViewHolder(ListAdapter.MyViewHolder holder, final int position) {

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, FavoriteActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("yourdata", yourdata);
                intent.putExtras(bundle);
                context.startActivity(intent);
            }
        });
    }

如果你使用 ListView 你可以试试

your_listview.setOnItemClickListener { parent, view, position, id ->   

  Intent intent = new Intent(context, FavoriteActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("yourdata", yourdata);
                intent.putExtras(bundle);
                context.startActivity(intent);
 }

FavoritActivity,您可以通过以下方式设置此数据:

String data= getIntent().getExtras().getString("yourdata");

我希望我理解正确。

【讨论】:

  • 对不起先生,但这不是我的问题。
【解决方案2】:

向您的列表项模型添加一个变量并使用它。 例如:

boolean isFavorite;

当您创建构造函数时所有项目false,当您单击星号列出时,将您的项目标志设为true

【讨论】:

    【解决方案3】:

    这段代码我用来打开最喜欢的活动,但这是用于与菜单按钮相同的活动,但我想从主要活动中打开最喜欢的片段。

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_favorites:
    
                favListFragment = new FavoriteListFragment();
                switchContent(favListFragment, FavoriteListFragment.ARG_ITEM_ID);
    
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    public void switchContent(Fragment fragment, String tag) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        while (fragmentManager.popBackStackImmediate());
    
        if (fragment != null) {
            FragmentTransaction transaction = fragmentManager
                    .beginTransaction();
            transaction.replace(R.id.content_frame, fragment, tag);
            //Only FavoriteListFragment is added to the back stack.
            if (!(fragment instanceof ProductListFragment)) {
                transaction.addToBackStack(tag);
            }
            transaction.commit();
            contentFragment = fragment;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      相关资源
      最近更新 更多