Я новичок в Android, просто новичок в kotlin.У меня есть приложение для Android с макетом вкладки и ViewPager.У меня есть два фрагмента для двух вкладок.Мне нужны некоторые значения из main.kt во фрагмент.kt Я не знаю, как передать значения из main.kt во фрагмент.kt.
В моем файле фрагмента .kt у меня есть вызовдругой класс, подобный этому
recyclerView.adapter = TransactionRecyclerAdapter(transactionList,appDatabase,direction,networkDefinitionProvider)
этот класс должен иметь аргументы, поэтому мне нужны значения из main.kt.
Я не могу передать значения в самом пакете, потому что значения возвращают типы, подобные этому
private val mfragmentAB = appDatabase
private val mfragmentIT: List<TransactionEntity>? = it
private val mfragmentINC : TransactionAdapterDirection? = incoming
private val mfragmentnetwork : NetworkDefinitionProvider? = networkDefinitionProvider
private val mfragmentviewpager : ViewPager? = viewPager
, поэтому сериализация и парскалирование не работают.так что, пожалуйста, проведите меня.
main.kt
private fun setupViewPager(viewPager: ViewPager, it: List<TransactionEntity>?, incoming: TransactionAdapterDirection) {
val incomingData = ArrayList<TransactionEntity>()
val outgoingData = ArrayList<TransactionEntity>()
val adapter = ViewPagerAdapter(supportFragmentManager, viewPager, it, incoming, appDatabase, networkDefinitionProvider)
if(incoming == INCOMING) {
if (it != null) {
incomingData.addAll(it)
}
}else {
if (it != null) {
outgoingData.addAll(it)
}
}
adapter.addFragment(ReceiveFragment(), "SEND")
adapter.addFragment(SendingFragment(), "RECEIVE")
viewPager.adapter = adapter
adapter.notifyDataSetChanged();
}
class ViewPagerAdapter(manager: FragmentManager, viewPager: ViewPager?, it: List<TransactionEntity>?, incoming: TransactionAdapterDirection?, appDatabase: AppDatabase?, networkDefinitionProvider: NetworkDefinitionProvider?) : FragmentPagerAdapter(manager)
{
private val mFragmentList: ArrayList<Fragment> = ArrayList<Fragment>()
private val mFragmentTitleList: ArrayList<String> = ArrayList<String>()
private val mfragmentAB = appDatabase
private val mfragmentIT: List<TransactionEntity>? = it
private val mfragmentINC : TransactionAdapterDirection? = incoming
private val mfragmentnetwork : NetworkDefinitionProvider? = networkDefinitionProvider
private val mfragmentviewpager : ViewPager? = viewPager
override fun getCount(): Int {
return mFragmentList.size
}
override fun getItem(position: Int): Fragment? {
var fragment: Fragment? = null
if (position == 0) {
fragment = SendingFragment()
} else if (position == 1) {
fragment = ReceiveFragment()
}
return fragment
}
fun addFragment(fragment: Fragment, title: String) {
mFragmentList.add(fragment)
mFragmentTitleList.add(title)
}
override fun getPageTitle(position: Int): CharSequence? {
return mFragmentTitleList[position]
}
override fun getItemPosition(fragItem: Any): Int {
var position = 0
if (fragItem is ReceiveFragment) {
position = 0
} else if (fragItem is SendingFragment) {
position = 1
}
return if (position >= 0) position else PagerAdapter.POSITION_NONE
}
}
frgment.kt
class ReceiveFragment : Fragment(){
private var linearLayoutManager: LinearLayoutManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.receive_fragment, container, false)
val recyclerView = rootView.findViewById<RecyclerView>(R.id.transaction_recycler_in) as RecyclerView
linearLayoutManager = LinearLayoutManager(getActivity(), LinearLayout.VERTICAL, false)
recyclerView.layoutManager = linearLayoutManager
recyclerView.adapter = TransactionRecyclerAdapter(transactionList,appDatabase,direction,networkDefinitionProvider)
recyclerView.setHasFixedSize(true);
return rootView
}
}
ОБНОВЛЕНИЕ
companion object {
/**
* new instance pattern for fragment
*/
@JvmStatic
fun newInstance(myObject: List<TransactionEntity>?): ReceiveFragment {
val newsFragment = ReceiveFragment()
val args = Bundle()
args.putParcelable(ARG_PARAM, myObject) ------**-Here i can not pass my values to onCreateView**
return newsFragment
}
}
UPADTE -1
companion object {
/**
* new instance pattern for fragment
*/
@JvmStatic
fun newInstance(myObject: List<TransactionEntity>?): ReceiveFragment {
val gson = Gson()
val model = myObject as List<TransactionEntity>
val json = gson.toJson(model)
System.out.println("json representation :" + json)
val bundle = Bundle()
bundle.putString("bundleValue", json)
val receiveFragment: ReceiveFragment = ReceiveFragment()
receiveFragment.setArguments(bundle)
return receiveFragment
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val gson = Gson()
val parsedValue = arguments!!.getString("bundleValue")
val turnsType = TypeToken<List<TransactionEntity>>() {}.type
//val animals = gson.fromJson(parsedValue,turnsType )
val animals = gson.fromJson(parsedValue, ) -------- how to get value here
и TypeToken - ошибка, показать нет конструктора