从带有条件的详细活动 recyclerview 打开新活动的方法

Method to open new activity from detail activity recyclerview with conditions

提问人:BUdiAKmal 提问时间:7/29/2022 最后编辑:Vishal VasaniBUdiAKmal 更新时间:7/30/2022 访问量:151

问:

Basic Layout Wireframe, and guide of what I want to ask

我会尽量清楚地解释我的意思,并尽可能多地解释。

*我希望你能从线框图:)理解我的意思


所以从线框图来看,我有 3 个活动。

  1. MainActivity,带有 TabLayout,其中填充了 Fragment,并且其中有一个 RecyclerView,

  2. DetailActivity,其中包含从 MainActivity 的每个 RecyclerView 项带来的数据 ,

  3. WebViewActivity,这将是用户单击 DetaiActivity 中的一个按钮后的最后一个活动,其中包含 与之前选择的每个 RecyclerView 项不同的上下文 用户。

从我描述的线框中,我已经成功打开了“WebViewActivity”,并使用“Button No.2”从“DetailActivity”中根据指定的参数(google.com)加载了URL

我的问题是:

  1. 当用户来时,如何打开 WebViewActivity 并加载“Youtube.com” 从“RecyclerView Item No.2”通过单击“按钮 1” 详细信息内部 活动?。

  2. 当用户来时,如何打开 WebViewActivity 并加载“Gmail.com” 从“RecyclerView Item No.3”通过单击“按钮 1” 详细信息内部 活动?。

这是我未解析的代码:

MainActivity.kt(主活动.kt)

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        setUpTabs() // Setup TabLayout


    } // End - OnCreate


    // Start - TabLayout
    private fun setUpTabs() {
        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(MainTabFragment(), "MainTab")
        viewPager_tabLayout.adapter = adapter
        tabs.setupWithViewPager(viewPager_tabLayout)
    } // End - TabLayout


} // End - Class

DetailActivity.kt (英语)

class DetailActivity : AppCompatActivity() {

    var prodBundle: Bundle? = null // Initialize getString (bundle) from MainActivity
    private var urls = arrayOfNulls<String>(3) // Initialize URL Direction

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_single_product)


        // Start - WebView URL to WebViewActivity
        urls[0] = "google.com"
        urls[1] = "youtube.com"
        urls[2] = "gmail.com"
        // End - WebView URL to WebViewActivity


        initView() // Setup getString from RecyclerView Main Activity


    } // End - OnCreate


    // Start - getString from RecyclerView Main Activity
    fun initView() {
        prodBundle = intent.extras

        ph_titleText.text = prodBundle?.getString("TitleText")
       ph_descText.text = prodBundle?.getString("DescText")
        prodBundle?.getString("ImageURL").let {
            Glide.with(this).asBitmap()
                .load(it)
                .into(ph_urlImage)

            Glide.with(this).asBitmap()
                .load(it)
                .centerCrop()
                .fitCenter()
                .placeholder(R.drawable.ph_img_none)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
        }
    } //  End  - getString from RecyclerView Main Activity

    
    // Start - putExtra to WebViewActivity
    fun button2(view: View) {
        val i = Intent(this@DetailActivity, WebViewActivity::class.java)
        i.putExtra("linksWeView", urls[0])
        startActivity(i)
    } // End - putExtra to WebViewActivity

} // End - Class

WebViewActivity.kt

class WebViewActivity : AppCompatActivity() {


    private lateinit var webView: WebView // Initialize WebView


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_webview)


        // Start - Assign getString URL from DetailActivity
        val intent = intent
        val webSite = intent.getStringExtra("linksWebView")
        // End - Assign getString URL from DetailActivity


        // Start - WebView
        webView = findViewById(R.id.wv)

        webView.setWebViewClient(object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                view?.visibility = View.INVISIBLE

                if (Build.VERSION.SDK_INT >= 19) {
                    webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
                } else {
                    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
                }
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                view?.visibility = View.VISIBLE
            }

            // Start - Fix SocialMedia Acces
            override fun shouldOverrideUrlLoading(wv: WebView, url: String): Boolean {
                if (url.startsWith("tel:") || url.startsWith("whatsapp:")) {
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.data = Uri.parse(url)
                    startActivity(intent)
                    webView.goBack()
                    return true
                }
                return false
            } // End - Fix SocialMedia Acces

        }) // End - WebView


        // Start - WebView Setting
        if (webSite != null) {
            webView.loadUrl(webSite)
        }

        val webSettings = webView.settings
        webSettings.javaScriptEnabled = true // js active
        webSettings.domStorageEnabled = true // componenet load
        webSettings.allowContentAccess = true
        webSettings.loadsImagesAutomatically = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH)
        webSettings.setEnableSmoothTransition(true)
        // End - WebView Setting


}// End - OnCreate

  
} // End - Class

MainTabFragment.kt

class MainTabFragment : Fragment() {


    lateinit var maintabfragmentAdapter: MainTabFragmentAdapter  // Initialize Adapter
    private val sLM = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) // Initialize layoutManager
    val addMainTabFragmentModelList: MutableList<MainTabFragmentModel> = ArrayList() // Initialize listModel
    private var urlMainTabFragment = arrayOfNulls<String>(2) // Initialize URL Direction WebView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_maintab, container, false)


    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // Start - Webview URL to WebViewActivity
        urlMainTabFragment[0] = "https://url1.com"
        urlMainTabFragment[1] = "https://url2.com"
        // End - Webview URL to WebViewActivity


        initViewMainTabFragment() // SetUp initView listModel
        actionMainTabFragment() // SetUp actionMainTabFragment
        iniRefreshListener() // SetUp swipeRefresh


    } // End - OnCreate


    // Start - intView listModel
    private fun initViewMainTabFragment() {
        rv_maintabfragment.layoutManager = sLM
        maintabfragmentAdapter = MainTabFragmentAdapter(requireActivity())
        rv_maintabfragment.adapter = maintabfragmentAdapter

        addMainTabFragmentModelList.add(
            MainTabFragmentModel("https://url1.com/img1.jpg", "TitleText#01", "DescText#01"))
        addMainTabFragmentModelList.add(
           MainTabFragmentModel("https://url1.com/img1.jpg", "TitleText#02", "DescText#02"))
        addMainTabFragmentModelList.add(
            MainTabFragmentModel("https://url1.com/img1.jpg", "TitleText#03", "DescText#03"))
        addMainTabFragmentModelList.add(
            MainTabFragmentModel("https://url1.com/img1.jpg", "TitleText#04", "DescText#04"))

        maintabfragmentAdapter.setMainTabFragment(addMainTabFragmentModelList)
    } // End - intView listModel


    // Start - putExtra to DetailActivity
    fun actionMainTabFragment() {
        maintabfragmentAdapter.setOnClickItemListenerMainTabFragment(object : OnItemClickListener {
            override fun onItemClick(item: View, position: Int) {
                lateinit var i: Intent
                if (position == 0) {
                    i = Intent(context, WebViewActivity::class.java)
                    i.putExtra("linksWebView", urlMainTabFragment[0])
                } else if (position == 3) {
                    i = Intent(context, WebViewActivity::class.java)
                    i.putExtra("linksWebView", urlMainTabFragment[1])
                } else {
                    i = Intent(context, DetailActivity::class.java)
                }
                i.putExtra("TitleText",
                    maintabfragmentAdapter.getMainTabFragment().get(position).titleTtextMainTab
                )
                i.putExtra(
                    "DescText",
                    maintabfragmentAdapter.getMainTabFragment().get(position).descTextMainTab
                )
                i.putExtra(
                    "ImageURL",
                    maintabfragmentAdapter.getMainTabFragment().get(position).imgMainTab
                )
                startActivity(i)
            }
        })
    } // End - putExtra to DetailActivity


} // End - Class

MainTabModel.kt

data class MainTabModel (var imgMainTab: String?, var titleTtextMainTab: String?, var descTextMainTab: String?)

OnItemClickListener.kt

interface OnItemClickListener {
    fun onItemClick(item: View, position:Int)
}

MianTabAdapter.kt

class MainTabAdapter(private val context: Context) :
    RecyclerView.Adapter<MainTabAdapter.MainTabViewHolder>() {

    private val MainTabModel: MutableList<MainTabModel> = mutableListOf()  // Initialize listModel
    private lateinit var onSelectedListenerMainTab: OnItemClickListener // Initialize onItemListener


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainTabViewHolder {
        return MainTabViewHolder(
            LayoutInflater.from(context).inflate(R.layout.item_maintab_layout, parent, false)
        )
    } // End - onCreateViewHolder

    
    override fun getItemCount(): Int {
        return MainTabModel.size
    }  // End - getItem

    
    override fun onBindViewHolder(holder: MainTabViewHolder, position: Int) {
        holder.maintabBindView(MainTabModel[position])
    } // End - onBindViewHolder

    
    // Start - setMainTab
    fun setMainTab(data: List<MainTabModel>) {
        MainTabModel.clear()
        MainTabModel.addAll(data)
        notifyDataSetChanged()
    } // End - setMainTab

    
    // Start - getMainTab
    fun getMainTab(): MutableList<MainTabModel> {
        return MainTabModel
    } // End - getMainTab

    
    // Start - MainTabViewHolder
    inner class MainTabViewHolder(maintabview: View) : RecyclerView.ViewHolder(maintabview) {
        val imgProdMainTab = maintabview.findViewById<ImageView>(R.id.iv_prodMainTab)
        val cvMainTab: MaterialCardView = maintabview.findViewById(R.id.cv_maintab)
        
        fun maintabBindView(MainTabModel: MainTabModel) {
            MainTabModel.apply {
                val image = MainTabModel.prodImgMainTab
                image.let {
                    Glide.with(itemView.context).asBitmap()
                        .load(it)
                        .into(imgProdMainTab)
                    
                    Glide.with(itemView.context).asBitmap()
                        .load(it)
                        .centerCrop()
                        .fitCenter()
                        .placeholder(R.drawable.ph_img_none)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .skipMemoryCache(true)
                        .transition(BitmapTransitionOptions.withCrossFade())
                }
            }
        }
        
        // Start - onClick
        init {
            cvMainTab.setOnClickListener { onSelectedListenerMainTab.onItemClick(it, layoutPosition) }
        } // End - onClick
        
    } // End - MainTabBindViewHolder


    // Start - OnItemListener
    fun setOnClickItemListenerMainTab(onItemClickListener: OnItemClickListener) {
        this.onSelectedListenerMainTab = onItemClickListener
    } // End - OnItemListener


} // End - Class

非常感谢您抽出宝贵时间,这肯定会花费很多精力来帮助我解决这个案子。:)

android kotlin android-recyclerview 条件语句 参数传递

评论


答:

0赞 Ticherhaz FreePalestine 7/29/2022 #1

您的问题中有太多代码,但到目前为止,我现在了解您想从点击事件继续到 .RecyclerViewWebViewActivity

你只需要简化它。您可以执行如下操作。修改您添加的新属性,即 .MainTabModellinkUrl

data class MainTabModel (
    var imgMainTab: String?, 
    var titleTtextMainTab: String?, 
    var descTextMainTab: String?, 
    var linkUrl: String?
)

之后,当您想从 中继续时,您只需要调用 .如下所示的示例(在 Recyclerview 单击的按钮处)。WebViewActivityRecyclerViewlinkUrl

val intent = Intent(this, WebViewActivity::class.java)
intent.putExtra("linkUrl", it.linkUrl)
startActivity(intent)

然后,在你的 ,只需检查是否包含你的。WebViewActivitygetIntentlinkUrl

我希望你能理解。

评论

0赞 BUdiAKmal 7/29/2022
感谢您的参与,但我在这里的意思是“当用户单击RecyclerView上的项目时,用户将转到” DetailActivity。kt“并带来 url 根据参数”,用户点击“DetailActivity.kt”上的“按钮 1”后,用户将转发并加载“WebViewActivity”上的“Url”。
0赞 Ticherhaz FreePalestine 7/30/2022
@BUdiAKmal 我仍然不明白你想做什么......
0赞 BUdiAKmal 7/30/2022
你能检查一下吗,我在那里简化了问题并更改了线框。谢谢
0赞 Ticherhaz FreePalestine 7/30/2022
@BUdiAKmal你可以查看@Razvan的评论,我不知道.除此之外,我看不出任何问题。 .那么问题出在哪里呢?只需对 URL 执行相同的操作I've been successfully pass the data, but how about the URL?
0赞 BUdiAKmal 7/30/2022
是的,我可以,如果只是为了传递数据。但是如何从 DetailActivity 转发到 WebViewActivity?.