1
zhujie
2025-04-15 879ec1ae04b37eb7bf9357903d10acc860d84d5b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package com.example.firstapp.ui.invitation
 
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Html
import android.util.TypedValue
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.example.firstapp.R
import com.example.firstapp.adapter.InvitationAdapter
import com.example.firstapp.adapter.InvitationRecordAdapter
import com.example.firstapp.entity.InvitationRecord
import com.example.firstapp.utils.PreferencesManager
import kotlin.math.abs
 
class InvitationActivity : AppCompatActivity() {
 
    private lateinit var recyclerSuccessView: RecyclerView
    private lateinit var recyclerRecordView: RecyclerView
    private lateinit var adapter: InvitationAdapter
    private lateinit var recordadapter: InvitationRecordAdapter
    private val data = mutableListOf<InvitationRecord>()
    private val recorddata = mutableListOf<InvitationRecord>()
    private val handler = Handler(Looper.getMainLooper())
    private val scrollInterval = 3000L
    private var currentScrollPosition = 0
    private var currentRecordScrollPosition = 0
    private var itemHeight = 0 // 动态存储item高度
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_invitation_main)
 
        // 初始化视图
        initViews()
 
        //初始化Adapter
        initSuccessAdapter()
 
        initRecorddapter()
 
        //加载数据
        loadData()
 
        loadRecordData()
 
        //启动轮播
        startAutoScroll()
 
        //分享
        val btnInvite = findViewById<Button>(R.id.btnInvite)
        btnInvite.setOnClickListener {
            shareImageToWechat()
        }
 
        //邀请码
        val invitationCodeText = findViewById<TextView>(R.id.invitationCodeText)
        invitationCodeText.text = "A1B2"
        //invitationCodeText.text = formatInvitationCode(PreferencesManager.getInviteCode());
        findViewById<Button>(R.id.copyButton).setOnClickListener {
            val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
            val clip = ClipData.newPlainText(
                "邀请码",
                invitationCodeText.text.toString().replace(" ", "") // 复制时去掉空格
            )
            clipboard.setPrimaryClip(clip)
            Toast.makeText(this, "已复制邀请码", Toast.LENGTH_SHORT).show()
        }
    }
 
    private fun initViews() {
        findViewById<TextView>(R.id.tv_notic).apply {
            text = Html.fromHtml(getString(R.string.invite_reward_text), Html.FROM_HTML_MODE_LEGACY)
        }
        recyclerSuccessView = findViewById(R.id.invitationsuccessRecyclerView)
        addSuccessListener()
 
        recyclerRecordView = findViewById(R.id.invitationrecordRecyclerView)
        addRecordListener()
    }
 
    private fun addSuccessListener() {
        recyclerSuccessView.viewTreeObserver.addOnGlobalLayoutListener {
            if (recyclerSuccessView.childCount > 0) {
                // 计算预期高度(60dp转px)
                val expectedHeight = dpToPx(60f)
                if (itemHeight != expectedHeight) {
                    // 修正所有item的高度
                    for (i in 0 until recyclerSuccessView.childCount) {
                        recyclerSuccessView.getChildAt(i).layoutParams.height = expectedHeight
                    }
                    // 请求重新布局
                    recyclerSuccessView.requestLayout()
                    itemHeight = expectedHeight
                }
            }
        }
        recyclerSuccessView.layoutManager = object : LinearLayoutManager(this@InvitationActivity) {
            override fun onMeasure(
                recycler: RecyclerView.Recycler, state: RecyclerView.State,
                widthSpec: Int, heightSpec: Int
            ) {
                if (itemHeight > 0) {
                    // 使用实际测量的高度
                    setMeasuredDimension(
                        View.resolveSize(widthSpec, width),
                        itemHeight
                    )
                } else {
                    // 默认高度60dp
                    val defaultHeight = TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 60f,
                        resources.displayMetrics
                    ).toInt()
                    setMeasuredDimension(
                        View.resolveSize(widthSpec, width),
                        defaultHeight
                    )
                }
            }
        }
    }
 
    private fun addRecordListener() {
        recyclerRecordView.viewTreeObserver.addOnGlobalLayoutListener {
            if (recyclerSuccessView.childCount > 0) {
                // 计算预期高度(60dp转px)
                val expectedHeight = dpToPx(60f)
                if (itemHeight != expectedHeight) {
                    // 修正所有item的高度
                    for (i in 0 until recyclerSuccessView.childCount) {
                        recyclerSuccessView.getChildAt(i).layoutParams.height = expectedHeight
                    }
                    // 请求重新布局
                    recyclerSuccessView.requestLayout()
                    itemHeight = expectedHeight
                }
            }
        }
        recyclerRecordView.layoutManager = object : LinearLayoutManager(this@InvitationActivity) {
            override fun onMeasure(
                recycler: RecyclerView.Recycler, state: RecyclerView.State,
                widthSpec: Int, heightSpec: Int
            ) {
                if (itemHeight > 0) {
                    // 使用实际测量的高度
                    setMeasuredDimension(
                        View.resolveSize(widthSpec, width),
                        itemHeight
                    )
                } else {
                    // 默认高度60dp
                    val defaultHeight = TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 60f,
                        resources.displayMetrics
                    ).toInt()
                    setMeasuredDimension(
                        View.resolveSize(widthSpec, width),
                        defaultHeight
                    )
                }
            }
        }
    }
 
    private fun initSuccessAdapter() {
        adapter = InvitationAdapter(this, data).apply {
            registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
                override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                    // 数据插入时检查高度
                    recyclerSuccessView.post {
                        if (recyclerSuccessView.childCount > 0) {
                            itemHeight = recyclerSuccessView.getChildAt(0).height
                        }
                    }
                }
            })
        }
        recyclerSuccessView.adapter = adapter
    }
 
    private fun initRecorddapter() {
        recordadapter = InvitationRecordAdapter(this, recorddata).apply {
            registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
                override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                    // 数据插入时检查高度
                    recyclerRecordView.post {
                        if (recyclerRecordView.childCount > 0) {
                            itemHeight = recyclerRecordView.getChildAt(0).height
                        }
                    }
                }
            })
        }
        recyclerRecordView.adapter = recordadapter
    }
 
    private fun loadData() {
        data.clear()
        data.addAll(
            listOf(
                InvitationRecord("H****e", "获得了1天会员", "已注册"),
                InvitationRecord("U****r", "获得了2天会员", "已注册"),
                InvitationRecord("A****e", "获得了免广告特权", "已注册"),
                InvitationRecord("B****e", "获得了3天会员", "已注册"),
                InvitationRecord("C****o", "获得了4天会员", "已注册")
            )
        )
        adapter.notifyDataSetChanged()
    }
 
    private fun loadRecordData() {
        recorddata.clear()
        recorddata.addAll(
            listOf(
                InvitationRecord("M****e", "", "未注册"),
                InvitationRecord("Q****r", "", "已注册"),
                InvitationRecord("W****e", "", "未注册"),
                InvitationRecord("E****e", "", "未注册"),
                InvitationRecord("R****o", "", "已注册")
            )
        )
        recordadapter.notifyDataSetChanged()
    }
 
    // 分享资源图片到微信
    private fun shareImageToWechat() {
        try {
            // 获取资源图片的URI
            val imageUri = Uri.parse("android.resource://${packageName}/${R.drawable.location}")
 
            val intent = Intent().apply {
                action = Intent.ACTION_SEND
                type = "image/*"
                putExtra(Intent.EXTRA_STREAM, imageUri)
                flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                setPackage("com.tencent.mm") // 指定微信包名
            }
 
            // 创建选择器,即使微信不可用也能选择其他应用
            val chooserIntent = Intent.createChooser(intent, "分享邀请图片")
 
            // 检查是否有应用能处理这个Intent
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(chooserIntent)
            } else {
                Toast.makeText(this, "未找到可分享的应用", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "分享失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
 
    private fun formatInvitationCode(code: String): String {
        return if (code.length > 2) {
            code.chunked(2).joinToString(" ")
        } else {
            code
        }
    }
 
    private val scrollRunnable = object : Runnable {
        override fun run() {
            if (data.isEmpty() || itemHeight <= 0) {
                handler.postDelayed(this, scrollInterval)
                return
            }
 
            // 使用取模运算确保位置在有效范围内
            currentScrollPosition++
            currentRecordScrollPosition++
 
            // 创建自定义平滑滚动器
            val smoothScroller = object : LinearSmoothScroller(this@InvitationActivity) {
                override fun getVerticalSnapPreference(): Int = SNAP_TO_START
 
                override fun calculateDyToMakeVisible(view: View, snapPreference: Int): Int {
                    // 计算需要滚动的距离,确保完整显示下一个item
                    val top = view.top
                    val height = view.height
                    return when {
                        snapPreference == SNAP_TO_START -> -top
                        snapPreference == SNAP_TO_END -> -(top - (recyclerSuccessView.height - height))
                        else -> -(top - (recyclerSuccessView.height / 2 - height / 2))
                    }
                }
 
                override fun calculateTimeForScrolling(dx: Int): Int {
                    // 根据滚动距离动态计算时间,保持匀速
                    return maxOf((500f * abs(dx) / itemHeight).toInt(), 200)
                }
            }.apply {
                targetPosition = currentScrollPosition
            }
 
            val smoothRecordScroller = object : LinearSmoothScroller(this@InvitationActivity) {
                override fun getVerticalSnapPreference(): Int = SNAP_TO_START
 
                override fun calculateDyToMakeVisible(view: View, snapPreference: Int): Int {
                    // 计算需要滚动的距离,确保完整显示下一个item
                    val top = view.top
                    val height = view.height
                    return when {
                        snapPreference == SNAP_TO_START -> -top
                        snapPreference == SNAP_TO_END -> -(top - (recyclerRecordView.height - height))
                        else -> -(top - (recyclerRecordView.height / 2 - height / 2))
                    }
                }
 
                override fun calculateTimeForScrolling(dx: Int): Int {
                    // 根据滚动距离动态计算时间,保持匀速
                    return maxOf((500f * abs(dx) / itemHeight).toInt(), 200)
                }
            }.apply {
                targetPosition = currentRecordScrollPosition
            }
 
            // 启动平滑滚动
            recyclerSuccessView.layoutManager?.startSmoothScroll(smoothScroller)
 
            recyclerRecordView.layoutManager?.startSmoothScroll(smoothRecordScroller)
 
            // 更智能的边界检测
            (recyclerSuccessView.layoutManager as? LinearLayoutManager)?.let { lm ->
                val lastVisible = lm.findLastVisibleItemPosition()
                val totalItems = adapter.itemCount
 
                // 当接近"虚拟列表"末尾时,跳转到中间位置
                if (lastVisible >= totalItems - 3) {
                    val jumpPosition = (totalItems / 2) * (Int.MAX_VALUE / totalItems)
                    currentScrollPosition = jumpPosition
                    recyclerSuccessView.scrollToPosition(jumpPosition)
                }
            }
 
            (recyclerRecordView.layoutManager as? LinearLayoutManager)?.let { lm ->
                val lastVisible = lm.findLastVisibleItemPosition()
                val totalItems = recordadapter.itemCount
 
                // 当接近"虚拟列表"末尾时,跳转到中间位置
                if (lastVisible >= totalItems - 3) {
                    val jumpPosition = (totalItems / 2) * (Int.MAX_VALUE / totalItems)
                    currentRecordScrollPosition = jumpPosition
                    recyclerRecordView.scrollToPosition(jumpPosition)
                }
            }
 
            handler.postDelayed(this, scrollInterval)
        }
    }
 
    private fun pxToDp(px: Int, context: Context): Int {
        return (px / (context.resources.displayMetrics.density)).toInt()
    }
 
    private fun dpToPx(dp: Float): Int {
        return (dp * resources.displayMetrics.density).toInt()
    }
 
    private fun startAutoScroll() {
        handler.removeCallbacks(scrollRunnable) // 先移除之前的回调
        handler.postDelayed(scrollRunnable, scrollInterval)
    }
 
    override fun onPause() {
        handler.removeCallbacks(scrollRunnable)
        super.onPause()
    }
 
    override fun onResume() {
        super.onResume()
        startAutoScroll()
    }
}