android -将数据从Activity传递到ViewPager中的片段

vxqlmq5t  于 2022-12-21  发布在  Android
关注(0)|答案(8)|浏览(224)

我有一个简单的Activity,其中包含TabLayout、ViewPager和2个片段。

public class ManagementCompanyOverviewActivity extends BaseActivity implements ManagementCompanyOverviewView {

    private ManagementCompanyVPAdapter mVPAdapter;
    private TabLayout mTLContent;
    private ViewPager mVPContent;

    @InjectPresenter
    ManagementCompanyPresenter mPresenter;

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

        mVPAdapter = new ManagementCompanyVPAdapter(getSupportFragmentManager());

        mTLContent = (TabLayout) findViewById(R.id.tl_company_content);

        mVPContent = (ViewPager) findViewById(R.id.vp_company_content);
        mVPContent.setAdapter(mVPAdapter);
        mTLContent.setupWithViewPager(mVPContent);
    }

    @Override
    public void onAboutCompanyInfoReceivedFromServer(AboutCompanyViewModel model) {

    }

Activity有一个Presenter(我使用的是Moxy),Presenter发送请求,获取应答,创建JavaObject(视图模型),并使用getViewState()将此模型传递给Activity。

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

    View view = inflater.inflate(R.layout.fragment_about_company, container, false);

    mTVName = (TextView) view.findViewById(R.id.tv_company_name);
    mTVDirector = (TextView) view.findViewById(R.id.tv_company_director);
    mTVWebsite = (TextView) view.findViewById(R.id.tv_company_website);
    mTVEmail = (TextView) view.findViewById(R.id.tv_company_email);
    mTVPhone = (TextView) view.findViewById(R.id.tv_company_phone);
    mTVSchedule = (TextView) view.findViewById(R.id.tv_company_schedule);
    mTVAddress = (TextView) view.findViewById(R.id.tv_company_address);

    return view;
}

这个片段有一些文本视图来显示来自我的模型的信息。如何传递这个模型?如果我知道它是正确的,我应该创建一个侦听器,但如何?我不完全了解如何与他们一起工作。

bxgwgixi

bxgwgixi1#

好吧,是我干的。
第1步:我在Activity中创建了公共接口,并为其创建了setter:

private OnAboutDataReceivedListener mAboutDataListener;

public interface OnAboutDataReceivedListener {
        void onDataReceived(AboutCompanyViewModel model);
    }

public void setAboutDataListener(OnAboutDataReceivedListener listener) {
    this.mAboutDataListener = listener;
}

第2步:我在我的Fragment中实现了这个接口并设置了监听器:

public class AboutCompanyFragment extends BaseFragment implements ManagementCompanyOverviewActivity.OnAboutDataReceivedListener

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            mActivity = (ManagementCompanyOverviewActivity) getActivity();
            mActivity.setAboutDataListener(this);
        }

第3步:我重写了接口的方法:

@Override
    public void onDataReceived(AboutCompanyViewModel model) {
        mPBName.setVisibility(View.INVISIBLE);
        mPBDirector.setVisibility(View.INVISIBLE);
        mPBWebsite.setVisibility(View.INVISIBLE);
        mPBEmail.setVisibility(View.INVISIBLE);
        mPBPhone.setVisibility(View.INVISIBLE);
        mPBSchedule.setVisibility(View.INVISIBLE);
        mPBAddress.setVisibility(View.INVISIBLE);

        mTVName.setVisibility(View.VISIBLE);
        mTVDirector.setVisibility(View.VISIBLE);
        mTVWebsite.setVisibility(View.VISIBLE);
        mTVEmail.setVisibility(View.VISIBLE);
        mTVPhone.setVisibility(View.VISIBLE);
        mTVSchedule.setVisibility(View.VISIBLE);
        mTVAddress.setVisibility(View.VISIBLE);

        mTVName.setText(model.getCompanyName());
        mTVDirector.setText(model.getDirectorName());
        mTVWebsite.setText(model.getWebsite());
        mTVEmail.setText(model.getEmail());
        mTVPhone.setText(model.getPhone());
        mTVSchedule.setText(model.getWorkTime());
        mTVAddress.setText(model.getAddress());
    }

就是这样。

tp5buhyn

tp5buhyn2#

在活动中尝试

public String sendData() {
        return YOUR_STRING;
    }

片段中

YOUR_ACTIVITY activity = (YOUR_ACTIVITY) getActivity();
String getData = activity.SendData();
0tdrvxhp

0tdrvxhp3#

您可以在Fragment中使用newInstance方法:

public static MyFragment newInstance(String parameter) {

        Bundle args = new Bundle();
        args.putString("parameter", parameter);
        SfCategoryFragment fragment = new SfCategoryFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            parameter = getArguments().getString("parameter");
        }
    }

在您的活动中:
使用MyFragment.newInstance("yourParam");代替new MyFragment()

ebdffaop

ebdffaop4#

您还可以在适配器的构造函数中获取要在片段中显示的数据,并在返回新片段之前设置参数

public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Weather weather;

ViewPagerAdapter(FragmentManager fm, Weather weather) {
    super(fm);
    this.weather = weather;
}

@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            Bundle bundle = new Bundle();
            WeatherFragment weatherFragment = new WeatherFragment();
            bundle.putParcelable("weather", weather);
            weatherFragment.setArguments(bundle);
            return weatherFragment;
        case 1:
            return new PoemFragment();
        default:
            return new EmptyFragment();
    }
}
w80xi6nr

w80xi6nr5#

从活动或视图分页器

Bundle bundle = new Bundle();
bundle.putParcelable(Keys.KEY_ITEM, cardResult);
CardItemFragment cardItemFragment = new CardItemFragment();
cardItemFragment.setArguments(bundle);

来自片段

@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
     getBundle();
}

private void getBundle() {
    bundle = getArguments();
    if (null != bundle) {
        if (bundle.containsKey(Keys.KEY_ITEM)) {
            cardResult = bundle.getParcelable(Keys.KEY_ITEM);
        }
    }
}
svujldwt

svujldwt6#

碎片

class SampleFragment : Fragment(), BaseFragmentInteraction {
    override fun updateFragmentData(data: String) {
        Toast.makeText(activity!!, data, Toast.LENGTH_SHORT).show()
    }
}

接口

interface BaseFragmentInteraction {
    fun updateFragmentData(data: String)
}

活动:

view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {

        override fun onPageSelected(position: Int) {
            val fragmentItem = (view_pager.adapter as FragmentPagerAdapter).getItem(view_pager.currentItem)
            (fragmentItem as BaseFragmentInteraction).updateFragmentData("SomeData")
        }

        override fun onPageScrollStateChanged(state: Int) {}

        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
    })

updateFragmetData方法将在当前选定的视图页导航项片段中调用。您还可以向updateFragmetData添加标记参数,以便确保调用了正确的片段示例。如果需要,您可以在updateFragmetData实现中调用isVisible,以确保片段可见。

i7uq4tfw

i7uq4tfw7#

我发现了一种新的方法来传递数据到片段,或片段适配器直接
首先你创建一个getter方法来获取数据假设你想获取username你在activity中创建一个方法

public String getUsername(){
return username;
}

然后从fragment和fragment适配器调用这个方法
碎片

(MainActivity) getActivity()).getUsername()

适配器

(MainActivity) context).getUsername()

这种方法还可以帮助您减少对数据库的请求数量

kx7yvsdv

kx7yvsdv8#

您可以通过两个简单的步骤将数据从Activity传递到片段或任何所需的片段(使用FragmentStatePagerAdapter时):

步骤1:将数据从Activity传递到ViewPagerAdapter类:要做到这一点,你需要添加另一个属性到构造函数中(attribut==your data)
步骤2:将数据从viewPagerAdapter类传递到fragment:现在,在createFragment()函数中,您可以使用bundle传递该属性
最后:接收片段中的数据

相关问题