我是移动开发的新手。我已经从Kotlin开始了我的移动应用程序。我有一个活动(ProductsActivity.kt),该活动通过ImageView和TextView加载RecyclerView并从独立工作的MySQL获取数据。现在,我希望将此Activity加载到Fragment中,我尝试使用Inflater加载,但它不显示任何数据。以下是我的代码,请帮助我如何实现相同的代码。预先感谢。
MainActivity.kt
package com.example.administrator.zmaart
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.app.Fragment
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
class MainActivity : AppCompatActivity(),
NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close)
drawer.addDrawerListener(toggle)
toggle.syncState()
val navigationView = findViewById<View>(R.id.nav_view) as
NavigationView
navigationView.setNavigationItemSelectedListener(this)
displaySelectedScreen(R.id.nav_home)
}
private var backButtonCount: Int = 0
override fun onBackPressed() {
val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
if (backButtonCount >= 1) {
val intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_HOME)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
} else {
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show()
backButtonCount++
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
return if (id == R.id.action_settings) {
true
} else super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
displaySelectedScreen(item.itemId)
return true
}
private fun displaySelectedScreen(itemId: Int) {
//creating fragment object
var fragment: Fragment? = null
//initializing the fragment object which is selected
when (itemId) {
R.id.nav_home -> fragment = home()
R.id.nav_orders -> fragment = orders()
R.id.nav_wishlist -> {
val intent = Intent(this@MainActivity,
ProductsActivity::class.java)
this@MainActivity.startActivity(intent)
}
R.id.nav_logout -> {
val sharedPreferences = getSharedPreferences("SharedPref", 0)
val editor = sharedPreferences.edit()
editor.clear()
editor.apply()
val intent = Intent(this@MainActivity, Login_Page::class.java)
this@MainActivity.startActivity(intent)
}
}
//replacing the fragment
if (fragment != null) {
val ft = supportFragmentManager.beginTransaction()
ft.replace(R.id.content_frame, fragment)
ft.commit()
}
val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout
drawer.closeDrawer(GravityCompat.START)
}
}
activity_products.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ProductsActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recylcerView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="745dp"
tools:layout_editor_absoluteY="-51dp" />
</RelativeLayout>
ProductsActivity.kt
package com.example.administrator.zmaart
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import org.json.JSONArray
import org.json.JSONException
import java.util.*
class ProductsActivity : AppCompatActivity() {
private lateinit var productList: MutableList<Product>
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_products)
recyclerView = findViewById(R.id.recylcerView1)
recyclerView.setHasFixedSize(false)
recyclerView.layoutManager = LinearLayoutManager(this)
productList = ArrayList()
loadProducts()
}
private fun loadProducts() {
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
val stringRequest = StringRequest(Request.Method.GET, URL_PRODUCTS,
Response.Listener { response ->
try {
//converting the string to json array object
val array = JSONArray(response)
//traversing through all the object
for (i in 0 until array.length()) {
//getting product object from json array
val product = array.getJSONObject(i)
//adding the product to product list
productList.add(Product(
product.getString("prod_id_sha"),
product.getString("prod_title"),
product.getDouble("prod_price"),
product.getDouble("prod_price2"),
product.getString("img_thumbnail")
))
}
//creating adapter object and setting it to recyclerview
val adapter = ProductsAdapter(this@ProductsActivity, productList)
recyclerView.adapter = adapter
} catch (e: JSONException) {
e.printStackTrace()
}
},
Response.ErrorListener { })
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest)
}
companion object {
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
private const val URL_PRODUCTS = "localhost/app/load_prod.php"
}
}
home.kt(我要在其中加载activity_products.xml的地方)
package com.example.administrator.zmaart
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class home : Fragment() {
private lateinit var productList: MutableList<Product>
private lateinit var recyclerView: RecyclerView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.activity_products, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity!!.title = "Home"
}
}
请告知我是否包含其他任何代码来帮助您。