** 我已经在这些 6 个项目上放置了按钮,现在我只需要当用户点击按钮时,它必须连接到 API 获取并显示内容。同样地,单击其他所有按钮都应连接到各自的 API。现在创建新活动和新适配器对于每个项目都是冗余代码,请告诉我如何正确实现这一点 **
home fragment
class Homefragment : Fragment() {
lateinit var buttondept:Button
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// 加载该片段的布局
val view= inflater.inflate(R.layout.fragment_homefragment, container, false)
buttondept=view.findViewById(R.id.btnDept)
buttondept.setOnClickListener {
val intent=Intent(context,descactivity::class.java)
intent.putExtra("option","department")
startActivity(intent)
}
return view
}
}
desc activity
class descactivity : AppCompatActivity() {
lateinit var recyclerDashBoard: RecyclerView
lateinit var layoutmanager: RecyclerView.LayoutManager
lateinit var recyclerAdapter:Horizontal_RecyclerView
lateinit var progressLayout: RelativeLayout
lateinit var progressBar: ProgressBar
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_descactivity)
val bookInfoList = arrayListOf<Book>()
recyclerDashBoard = findViewById(R.id.recyclerDashboard)
progressBar = findViewById(R.id.progressbar)
progressLayout = findViewById(R.id.progresslayout)
progressLayout.visibility = View.VISIBLE
val intent=getIntent()
val selectionOption= intent.getStringExtra("option")
val queue = Volley.newRequestQueue(this as Context)
val url = "http://13.235.250.119/v1/book/fetch_books/"
if (ConnectionManager().checkConnectivity(this as Context)) {
val jsonObjectRequest =
object : JsonObjectRequest(Method.GET, url, null, Response.Listener {
try {
progressLayout.visibility = View.GONE
val success = it.getBoolean("success")
if (success) {
val data = it.getJSONArray("data")
for (i in 0 until data.length()) {
val bookJSONObject = data.getJSONObject(i)
val bookobject = Book(
bookJSONObject.getString("book_id"),
bookJSONObject.getString("name"),
bookJSONObject.getString("author"),
bookJSONObject.getString("rating"),
bookJSONObject.getString("price"),
bookJSONObject.getString("image")
)
bookInfoList.add(bookobject)
layoutmanager = LinearLayoutManager(this)
recyclerAdapter =
Horizontal_RecyclerView(this as Context, bookInfoList)
recyclerDashBoard.adapter = recyclerAdapter
recyclerDashBoard.layoutManager = layoutmanager
}
} else {
Toast.makeText(
this as Context,
"some error occurred!!",
Toast.LENGTH_SHORT
).show()
}
} catch (e: JSONException) {
Toast.makeText(
this as Context,
"some unknown error occured!!",
Toast.LENGTH_SHORT
).show()
}
}, Response.ErrorListener {
Toast.makeText(
this as Context,
"volley error occured!!",
Toast.LENGTH_SHORT
).show()
}) {
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers["content-type"] = "application/json"
headers["token"] = "a07daa7f3efb3b"
return headers
}
}
queue.add(jsonObjectRequest)
}
}
}