我有一个用Kotlin开发的android
应用。我的一个活动是使用viewpager进行tabview来显示两个选项卡,但是这里我只显示一个选项卡,而另一个则不显示。活动仅显示一个标签。我犯错了,请指导我。
private fun setupViewPager(viewPager: ViewPager, it: List<TransactionEntity>?, incoming: TransactionAdapterDirection) {
val adapter = ViewPagerAdapter(supportFragmentManager, viewPager, it, incoming, appDatabase, networkDefinitionProvider)
if(adapter.count < 2) {
if (incoming.equals(OUTGOING)) {
adapter.addFragment(SendingFragment(it!!, appDatabase, OUTGOING, networkDefinitionProvider), "SEND")
} else if (incoming.equals(INCOMING)) {
adapter.addFragment(ReceiveFragment(it!!, appDatabase, INCOMING, networkDefinitionProvider), "RECEIVE")
}
viewPager.setCurrentItem(0)
viewPager.adapter = adapter
}
}
我的猜测是,在getItem()方法中仅设置一个frament
inner class ViewPagerAdapter(manager: FragmentManager, viewPager: ViewPager, it: List<TransactionEntity>?, incoming: TransactionAdapterDirection, appDatabase: AppDatabase, networkDefinitionProvider: NetworkDefinitionProvider) : FragmentStatePagerAdapter(manager) {
private val mFragmentList = ArrayList<Fragment>()
private val mFragmentTitleList = ArrayList<String>()
private val mfragmentAB = appDatabase
private val mfragmentIT: List<TransactionEntity> = it!!
private val mfragmentINC : TransactionAdapterDirection = incoming
private val mfragmentnetwork : NetworkDefinitionProvider = networkDefinitionProvider
/* override fun getItem(position: Int): Fragment {
return mFragmentList[position]
}*/
/*override fun getItem(position: Int): Fragment {
val fragment1 = ReceiveFragment(mfragmentIT,mfragmentAB,mfragmentINC,mfragmentnetwork)
return fragment1
}*/
override fun getItem(position: Int): Fragment? {
var fragment: Fragment? = null
if (position == 0) {
fragment = ReceiveFragment(mfragmentIT,mfragmentAB,mfragmentINC,mfragmentnetwork)
} else if (position == 1) {
fragment = SendingFragment(mfragmentIT,mfragmentAB,mfragmentINC,mfragmentnetwork)
}
return fragment
}
override fun getCount(): Int {
return mFragmentList.size
}
fun addFragment(fragment: Fragment, title: String) {
mFragmentList.add(fragment)
mFragmentTitleList.add(title)
}
override fun getPageTitle(position: Int): CharSequence {
return mFragmentTitleList[position]
}
/*override fun getItemPosition(`object`: Any): Int {
return PagerAdapter.POSITION_NONE
}*/
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
}
}
我的完整代码:
class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener, KodeinAware {
//tab
private var tabLayout: TabLayout? = null
var viewPager: ViewPager? = null
//private val tabIcons = intArrayOf(R.drawable.receive_tab, R.drawable.send_tab)
//end
/*private var tabLayout: TabLayout? = null
var viewPager: ViewPager? = null
private var viewPagerAdapter: ViewPagerAdapter? = null*/
//end
override val kodein by closestKodein()
val adapter = ViewPagerAdapter(supportFragmentManager)
private val actionBarDrawerToggle by lazy { ActionBarDrawerToggle(this, drawer_layout, R.string.drawer_open, R.string.drawer_close) }
private val syncProgressProvider: SyncProgressProvider by instance()
private val networkDefinitionProvider: NetworkDefinitionProvider by instance()
private val appDatabase: AppDatabase by instance()
private val settings: Settings by instance()
private val currentTokenProvider: CurrentTokenProvider by instance()
private val currentAddressProvider: CurrentAddressProvider by instance()
private var lastNightMode: Int? = null
private var balanceLiveData: LiveData<Balance>? = null
private var etherLiveData: LiveData<Balance>? = null
private val onboardingController by lazy { OnboardingController(this, settings) }
private var lastPastedData: String? = null
var t1: Int = 0
override fun onResume() {
super.onResume()
if (lastNightMode != null && lastNightMode != settings.getNightMode()) {
val intent = intent
finish()
startActivity(intent)
//recreateWhenPossible()
return
}
lastNightMode = settings.getNightMode()
setCurrentBalanceObservers()
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
if (clipboard.hasPrimaryClip()) {
val item = clipboard.primaryClip.getItemAt(0).text?.toString()
val erc681 = item?.let { EthereumURI(it).toERC681() }
if (erc681?.valid == true && erc681?.address != null && item != lastPastedData && item != currentAddressProvider.value?.hex.let { ERC681(address = it).generateURL() }) {
Snackbar.make(fab, R.string.paste_from_clipboard, Snackbar.LENGTH_INDEFINITE)
.addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar>() {
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
if (event == DISMISS_EVENT_ACTION || event == DISMISS_EVENT_SWIPE) {
lastPastedData = item
}
}
})
.setAction(R.string.paste_from_clipboard_action, {
alert(R.string.copied_string_warning_message, R.string.copied_string_warning_title) {
startActivity(Intent(this@MainActivity, CreateTransactionActivity::class.java).apply {
data = Uri.parse(item)
})
}
})
.show()
}
}
}
private fun String.isJSONKey() = try {
JSONObject(this).let {
it.has("address") && (it.has("crypto") || it.has("Crypto"))
}
} catch (e: Exception) {
false
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (data != null && data.hasExtra("SCAN_RESULT")) {
val scanResult = data.getStringExtra("SCAN_RESULT")
when {
scanResult.isEthereumURLString() -> {
startActivity(getEthereumViewIntent(scanResult))
}
scanResult.length == 64 -> {
startActivity(getKeyImportIntent(scanResult, KeyType.ECDSA))
}
scanResult.isJSONKey() -> {
startActivity(getKeyImportIntent(scanResult, KeyType.JSON))
}
/*scanResult.isUnsignedTransactionJSON() || scanResult.isSignedTransactionJSON() || scanResult.isParityUnsignedTransactionJSON() -> {
startActivity(getOfflineTransactionIntent(scanResult))
}*/
scanResult.startsWith("0x") -> {
startActivity(getEthereumViewIntent(ERC681(address = scanResult).generateURL()))
}
else -> {
AlertDialog.Builder(this)
.setMessage(R.string.scan_not_interpreted_error_message)
.setPositiveButton(android.R.string.ok, null)
.show()
}
}
}
}
fun refresh() {
val incomingSize = transaction_recycler_in.adapter?.itemCount ?: 0
val outgoingSize = transaction_recycler_out.adapter?.itemCount ?: 0
val hasTransactions = incomingSize + outgoingSize > 0
//empty_view_container.setVisibility(!hasTransactions && !onboardingController.isShowing)
transaction_recycler_out.setVisibility(hasTransactions)
transaction_recycler_in.setVisibility(hasTransactions)
//remove the textview based on the condition
if(hasTransactions.equals(true)){
empty_view.setVisibility(View.GONE)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
//val dateFormat = android.text.format.DateFormat.getDateFormat(applicationContext)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_in_drawer_container)
onboardingController.install()
settings.registerListener(this)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
drawer_layout.addDrawerListener(actionBarDrawerToggle)
receive_button.setOnClickListener {
onboardingController.dismiss()
startActivityFromClass(RequestActivity::class)
}
send_button.setOnClickListener {
startActivityFromClass(CreateTransactionActivity::class)
}
fab.setOnClickListener {
startScanActivityForResult(this)
}
transaction_recycler_out.layoutManager = LinearLayoutManager(this)
transaction_recycler_in.layoutManager = LinearLayoutManager(this)
current_fiat_symbol.setOnClickListener {
startActivityFromClass(SelectReferenceActivity::class)
}
current_token_symbol.setOnClickListener {
startActivityFromClass(SelectTokenActivity::class)
}
syncProgressProvider.observe(this, Observer {
val progress = it!!
if (progress.isSyncing) {
val percent = ((progress.currentBlock.toDouble() / progress.highestBlock) * 100).toInt()
supportActionBar?.subtitle = "Block ${progress.currentBlock}/${progress.highestBlock} ($percent%)"
}
})
val incomingTransactionsObserver = Observer<List<TransactionEntity>> {
Log.e("INDIA", "incomingTransactionsObserver : " + it);
if (it != null) {
viewPager = findViewById(R.id.viewpager)
t1++
setupViewPager(viewPager!!, it, INCOMING)
tabLayout = findViewById(R.id.tabs);
tabLayout!!.setupWithViewPager(viewPager)
transaction_recycler_in.adapter = TransactionRecyclerAdapter(it, appDatabase, INCOMING, networkDefinitionProvider)
transaction_recycler_in.setVisibility(!it.isEmpty())
refresh()
}
}
val outgoingTransactionsObserver = Observer<List<TransactionEntity>> {
Log.e("INDIA", "outgoingTransactionsObserver : " + it);
if (it != null) {
viewPager = findViewById(R.id.viewpager)
t1++
setupViewPager(viewPager!!, it, OUTGOING)
tabLayout = findViewById(R.id.tabs);
tabLayout!!.setupWithViewPager(viewPager)
transaction_recycler_out.adapter = DuplicateTransactionRecyclerAdapter(it, appDatabase, OUTGOING, networkDefinitionProvider)
refresh()
}
}
var incomingTransactionsForAddress: LiveData<List<TransactionEntity>>? = null
var outgoingTransactionsForAddress: LiveData<List<TransactionEntity>>? = null
//fun installTransactionObservers() {
fun installTransactionObservers() {
incomingTransactionsForAddress?.removeObserver(incomingTransactionsObserver)
outgoingTransactionsForAddress?.removeObserver(outgoingTransactionsObserver)
currentAddressProvider.value?.let { currentAddress ->
val currentChain = networkDefinitionProvider.getCurrent().chain
incomingTransactionsForAddress = appDatabase.transactions.getIncomingTransactionsForAddressOnChainOrdered(currentAddress, currentChain)
outgoingTransactionsForAddress = appDatabase.transactions.getOutgoingTransactionsForAddressOnChainOrdered(currentAddress, currentChain)
incomingTransactionsForAddress?.observe(this, incomingTransactionsObserver)
outgoingTransactionsForAddress?.observe(this, outgoingTransactionsObserver)
}
}
networkDefinitionProvider.observe(this, Observer {
setCurrentBalanceObservers()
installTransactionObservers()
})
currentAddressProvider.observe(this, Observer {
installTransactionObservers()
})
currentAddressProvider.observe(this, Observer { _ ->
setCurrentBalanceObservers()
})
if (intent.action?.equals("org.walleth.action.SCAN") == true) {
startScanActivityForResult(this)
}
if (savedInstanceState != null) {
lastPastedData = savedInstanceState.getString(KEY_LAST_PASTED_DATA)
}
//progressBar.visibility = View.VISIBLE
}
private val balanceObserver = Observer<Balance> {
if (it != null) {
/* val progressBar: ProgressBar = this.progressBar1
progressBar.visibility = View.GONE*/
value_view.setValue(it.balance, currentTokenProvider.currentToken)
supportActionBar?.subtitle = getString(R.string.main_activity_block, it.block)
} else {
value_view.setValue(ZERO, currentTokenProvider.currentToken)
supportActionBar?.subtitle = getString(R.string.main_activity_no_data)
}
}
private val etherObserver = Observer<Balance> {
if (it != null) {
send_button.setVisibility(it.balance > ZERO, INVISIBLE)
} else {
send_button.visibility = INVISIBLE
}
}
private fun setCurrentBalanceObservers() {
Log.e("INDIA","currentAddress")
val currentAddress = currentAddressProvider.value
Log.e("INDIA","currentAddress" + currentAddress)
if (currentAddress != null) {
balanceLiveData?.removeObserver(balanceObserver)
balanceLiveData = appDatabase.balances.getBalanceLive(currentAddress, currentTokenProvider.currentToken.address, networkDefinitionProvider.getCurrent().chain)
balanceLiveData?.observe(this, balanceObserver)
etherLiveData?.removeObserver(etherObserver)
etherLiveData = appDatabase.balances.getBalanceLive(currentAddress, getEthTokenForChain(networkDefinitionProvider.getCurrent()).address, networkDefinitionProvider.getCurrent().chain)
etherLiveData?.observe(this, etherObserver)
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
actionBarDrawerToggle.syncState()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
actionBarDrawerToggle.onConfigurationChanged(newConfig)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.menu_copy -> {
copyToClipboard(currentAddressProvider.getCurrent(), fab)
true
}
/*R.id.menu_info -> {
startActivityFromClass(InfoActivity::class.java)
true
}*/
else -> actionBarDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item)
}
override fun onSharedPreferenceChanged(preferences: SharedPreferences?, key: String?) {
if (Settings::currentFiat.name == key) {
transaction_recycler_in.adapter?.notifyDataSetChanged()
transaction_recycler_in.adapter?.notifyDataSetChanged()
}
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState!!.putString(KEY_LAST_PASTED_DATA, lastPastedData)
}
override fun onDestroy() {
settings.unregisterListener(this)
super.onDestroy()
}
//tab
private fun setupViewPager(viewPager: ViewPager, it: List<TransactionEntity>?, incoming: TransactionAdapterDirection) {
//val adapter = ViewPagerAdapter(supportFragmentManager, viewPager, it, incoming, appDatabase, networkDefinitionProvider)
if(adapter.count < 2) {
if (t1 == 1) {
adapter.addFragment(ReceiveFragment(it!!, appDatabase, INCOMING, networkDefinitionProvider), "SEND")
} else {
adapter.addFragment(SendingFragment(it!!, appDatabase, OUTGOING, networkDefinitionProvider), "RECEIVE")
}
if (t1 == 2) {
viewPager.adapter = adapter
}
}
}
//class ViewPagerAdapter(manager: FragmentManager, viewPager: ViewPager, it: List<TransactionEntity>?, incoming: TransactionAdapterDirection, appDatabase: AppDatabase, networkDefinitionProvider: NetworkDefinitionProvider) : FragmentStatePagerAdapter(manager) {
//class ViewPagerAdapter(manager: FragmentManager, viewPager: ViewPager, it: List<TransactionEntity>?, incoming: TransactionAdapterDirection, appDatabase: AppDatabase, networkDefinitionProvider: NetworkDefinitionProvider) : FragmentPagerAdapter(manager)
class ViewPagerAdapter(manager: FragmentManager) : FragmentStatePagerAdapter(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(mfragmentIT, mfragmentAB, mfragmentINC, mfragmentnetwork)
} else if (position == 1) {
fragment = ReceiveFragment(mfragmentIT, mfragmentAB, mfragmentINC, mfragmentnetwork)
}
return fragment
}*/
override fun getItem(position: Int) = mFragmentList[position]
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
}
}
}
答案 0 :(得分:0)
尝试类似的东西:
class ViewPagerAdapter(manager: FragmentManager) : FragmentStatePagerAdapter(manager)
{
val incomingData: List<TransactionEntity> = mutableListOf()
val outgoingData: List<TransactionEntity> = mutableListOf()
override fun getCount(): Int = 2
override fun getItem(position: Int): Fragment {
return if (position == 0) SendingFragment(outgoingData, mfragmentAB, OUTGOING, mfragmentnetwork)
else ReceiveFragment(incomingData, mfragmentAB, INCOMING, mfragmentnetwork)
}
fun updateData(data: List<TransactionEntity>, isIncoming: Boolean) {
if (isIncoming) {
incomingData.clear()
incomingData.addAll(data)
} else {
outgoingData.clear()
outgoingData.addAll(data)
}
notifyDataSetChanged()
}
...
UPD
class MainActivity {
val incomingData: List<TransactionEntity> = mutableListOf()
val outgoingData: List<TransactionEntity> = mutableListOf()
...
private fun setupViewPager(viewPager: ViewPager, it: List<TransactionEntity>?, incoming: TransactionAdapterDirection) {
val adapter = ViewPagerAdapter(supportFragmentManager, viewPager, it, incoming, appDatabase, networkDefinitionProvider)
if(incoming == INCOMING) {
incomingData.clear()
incomingData.addAll(data)
} else {
outgoingData.clear()
outgoingData.addAll(data)
}
adapter.addFragment(ReceiveFragment(incomingData, appDatabase, INCOMING, networkDefinitionProvider), "SEND")
adapter.addFragment(SendingFragment(outgoingData, appDatabase, OUTGOING, networkDefinitionProvider), "RECEIVE")
viewPager.adapter = adapter
}
...
}