通过改造获取片段中的数据

时间:2018-12-12 10:25:15

标签: android kotlin

在这个问题上,我想从我的API中获取数据

我从翻新中获取数据

我想在“片段”选项卡的RecyclerView中显示数据,但是如何将数据从活动发送到“片段”

这就是我尝试过的所有内容

为我提供帖子的ArrayList的改造电话

getMainApp().swiftAPI.getPosts().enqueue(object : Callback<ArrayList<Post>>{
            override fun onFailure(call: Call<ArrayList<Post>>?, t: Throwable?) {
                Toast.makeText(this@DashboardActivity, t?.message, Toast.LENGTH_SHORT)
            }

            override fun onResponse(call: Call<ArrayList<Post>>?, response: Response<ArrayList<Post>>?) {
                if (response?.isSuccessful!!){

                }
            }

PagesFragment

val rootView = inflater.inflate(R.layout.fragment_page, container, false)
        val video_recyclerview = rootView.findViewById(R.id.pages_rcv) as RecyclerView // Add this
        video_recyclerview.layoutManager = LinearLayoutManager(activity)
        video_recyclerview.adapter = PagesAdapter()
        return rootView

我想知道是否有任何方法可以将ArrayList发送到片段,因为我的数据在ArrayList中 As shown in Picture

4 个答案:

答案 0 :(得分:1)

您可以在活动中定义一个接口,然后让该片段实现该接口。您可以在我的github上遵循以下示例:ActivityToFragmentCommunication

基本上,在您的活动中定义:

  public interface DataLoadedListener {
        public void onDataLoaded(ArrayList<Post> posts);
    }

然后,使您的片段实现如下所示的接口:

public class ExampleFragment extends Fragment implements MainActivity.DataLoadedListener {

  // your fragment code
}

最后在您活动的onCreate()方法中:

// Create new fragment and transaction
        mExampleFragment = new ExampleFragment();
        // setting mExampleFragment as data load listener
        mDataLoadedListener = (DataLoadedListener) mExampleFragment;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack if needed
        transaction.replace(R.id.flContainer, mExampleFragment);
        transaction.addToBackStack(null);
        // Commit the transaction
        transaction.commit();

        // load data after click
        btLoadData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadData();
                // notify attached fragment
                mDataLoadedListener.onDataLoaded(myStrings);
            }
        });

答案 1 :(得分:0)

您可以在updateData中定义类似PagesFragment的方法

    lateinit var adapter

    public fun onCreateView....
        val rootView = inflater.inflate(R.layout.fragment_page, container, false);
        val video_recyclerview = rootView.findViewById(R.id.pages_rcv) as RecyclerView // Add this
        video_recyclerview.layoutManager = LinearLayoutManager(activity)
        adapter = PagesAdapter()
        video_recyclerview.adapter = adapter
        return rootView
    }

    public fun updateData(posts:List<Post>){
        adapter.notifyDataSetChange()
    }

,然后通过您的活动(例如通过PageFragment实例)调用它:

pageFragment.updateData(posts)

答案 2 :(得分:0)

首先在您的活动课堂中检查currentFragment。您将在活动类中获得片段参考对象。因此该示例如下所示:

假设您有一个名为DataFragment的片段,并且在活动类中有一个引用mDataFragment。现在,当您在活动类中获取数据时,您将调用((DataFragment)mDataFragment).passData(yourDataList).,请记住passData()是您的片段类中的公共方法。然后,您可以在adapter中添加数据并调用notifyDataSetChanged()

答案 3 :(得分:0)

由于您使用的是Android系统,因此我建议您使用ViewModel组件,该组件可以非常轻松地在活动及其片段之间进行通信。

首先将软件包添加到您的应用中

    implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'

然后创建一个ViewModel类

public class MyViewModel extends ViewModel {
    public MutableLiveData<ArrayList<Post>> posts = new MutableLiveData<ArrayList<Post>>();
}

现在该片段中已订阅它。

 public class DetailFragment extends Fragment {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        model.posts.observe(this, { posts ->
           // Update the UI.
        });
    }
 }

然后如下所示在MainActivity中设置值,瞧,片段中就有数据了。您可以详细了解here

public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        // Create a ViewModel the first time the system calls an activity's onCreate() method.
        // Re-created activities receive the same MyViewModel instance created by the first activity.

        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.users.setValue(posts);
    }
}