【问题标题】:How To Pass data From Intent To Fragment如何将数据从 Intent 传递到 Fragment
【发布时间】:2021-07-12 00:52:59
【问题描述】:

我是 kotlin 的新手,我想将我的活动中的数据发送到我的选项卡片段,所以在用户数据之后,我想显示与用户相关的关注者并在同一活动中使用选项卡片段进行关注,所以我创建了2 个片段,并尝试将 ArrayList 发送到两个片段

    val listdata: Account? =intent.getParcelableExtra(EXTRA_DATAS)
        if (listdata != null) {
                name.text = listdata.name
                username.text = listdata.username
                company.text = "${listdata.company} , ${listdata.location}"
                repository.text = "${listdata.repository}  total repo"
                following.text = "${listdata.following} following"
                followers.text = "${listdata. followers}  followers"

                this.title = listdata.username
             url_followers = "https://api.github.com/users/${listdata.username}/followers"
             url_followings = "https://api.github.com/users/${listdata.username}/following"

            Glide.with(this)
                .load(listdata.avatar)
                .into(imgPhoto)

        }
        ShowViewPager()
        getData(url_followers) //this return arraylist
        getData(url_followings) //this return arraylist

        val fragment = FollowersFragment.newInstance(getData(url_followers))
        val bundle = Bundle()
        bundle.putString("HaloHalo","coba")
        val fragfollowers = FollowersFragment()
        fragfollowers.setArguments(bundle);
        supportFragmentManager.beginTransaction().add(FollowersFragment(),"hihi").commit()

//        val bundle2 = Bundle()
//        bundle2.putParcelableArrayList(FollowingFragment.EXTRA_DATA,getData(url_followings))
//        val transaction2 = supportFragmentManager.beginTransaction()
//        val fragfollowers2 = FollowingFragment()
//        fragfollowers2.arguments = bundle2
//        transaction2.commit()

这就是我获取数据的方式,但它没有显示任何数据,只是 null 这是我在 FollowersFragment 中的伴生对象

companion object {
        private var list: ArrayList<Account> = arrayListOf()
        fun newInstance(data: ArrayList<Account>)= FollowersFragment().apply  {
            val fragment = FollowersFragment()
            val args = Bundle()
            args.putString("punten", "coba coba")
            fragment.setArguments(args)
            return fragment
        }


    }

这是我的followersFragment中的onCreateView函数

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootview = inflater.inflate(R.layout.fragment_followers, container, false)

        // Inflate the layout for this fragment
        var sect : TextView = rootview.findViewById(R.id.section_label_followers)
//        list = this.getParcelableArrayList<Account>(EXTRA_DATA)
//        val test = arguments
        var bundle = arguments
        var cak = bundle?.getString("hihi")
        var cek = bundle?.getString("punten")

        sect.text = cak + cek
        return rootview
    }

当我尝试 arraylist 并失败时,我认为这个问题是由我的空 araylist 引起的,但是在我尝试使用上面的代码之类的字符串之后,它仍然没有发送任何一个,你能帮我解决这个问题吗?

我使用 pageadapter,这是我的页面

private fun ShowViewPager() {
        val sectionsPagerAdapter = SectionsPagerAdapter(this)
        val viewPager: ViewPager2 = findViewById(R.id.viewPager)
        viewPager.adapter = sectionsPagerAdapter
        val tabs: TabLayout = findViewById(R.id.tabLayout)
        TabLayoutMediator(tabs, viewPager) { tab, position ->
            tab.text = resources.getString(TAB_TITLES[position])
        }.attach()
        supportActionBar?.elevation = 0f
        
    }

【问题讨论】:

  • 所以你的片段在 viewpager 上并且你的 viewpager 附加了活动对吗??
  • @D_K 是的,但我不知道如何传递数据

标签: android kotlin android-fragments android-fragmentactivity


【解决方案1】:

首先在您的 Activity 文件中创建一个函数以将数据传递给寻呼机适配器,如下所示:

DialPadPagerAdapter pagerAdapter = new DialPadPagerAdapter(getSupportFragmentManager(), PagerAdapter.POSITION_NONE, tabList, contactsArrayList);

pagerAdapter.refreshList(list,position);

在您的 pagerAdapter 类中使用另一个 refreshList() 将数据传递给片段

public void refreshList(ArrayList<CallogsList> list, int position) {
        contactArrayList = list;

        if (position == 0) {
            Fragment1.refreshList(contactArrayList);
        } else if (position == 1) {
            Fragment2.refreshList(contactArrayList);
        }
    }

在你的片段中(两个片段相同)

 public static void refreshList(ArrayList<CallogsList> list) {
       // your adapter to send the arraylist
        adapter.refreshList(list);
        
    }

在适配器类中添加这个函数

 public void refreshList(ArrayList<CallogsList> list) {
        yourList = list;
        notifyDataSetChanged();
    }

【讨论】:

  • 所以首先我必须将数据发送到 pageradapter 对吗?但我仍然找不到在 kotlin 中编写 DialPadPagerAdapter 的方法,
  • 新建kotlin并添加这个代码编辑器会自己处理并自动转换成kotlin
【解决方案2】:

我认为您应该通过构造函数将数据传递给适配器 -> 将数据传递给 NewInstance Fragment。我试过了,成功了。

关注代码片段:

适配器:

class ViewPagerAdapter(fragmentActivity: FragmentActivity, private val listData: ArrayList<Int>) :
FragmentStateAdapter(fragmentActivity) {
override fun getItemCount() = 2

override fun createFragment(position: Int): Fragment {
    when (position) {
        1 -> {
            return FragmentOne.newInstance(listData)
        }
    }
    return FragmentTwo.newInstance(listData)
}

}

片段:

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    arguments?.let {
        val data  = it.getIntegerArrayList("Key")
        Log.e("Namlxcntt", " Fragment Two -> ${data?.toArray()} ")
    }
}
companion object {

    @JvmStatic
    fun newInstance(listData: ArrayList<Int>) =
        FragmentTwo().apply {
            arguments = Bundle().apply {
                putIntegerArrayList("Key", listData)
            }
        }
}

【讨论】:

  • 嘿,加个sn-p代码让OP理解就好了。
猜你喜欢
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 2021-05-12
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
相关资源
最近更新 更多