首页 > 解决方案 > 如何从收件箱移动到 kotlin/android.. 中的对话选项卡?

问题描述

我已经编写了收件箱活动和对话活动的代码,但不明白当用户单击收件箱选项卡中的任何消息时如何移动到对话选项卡..?**注意:**我的应用是离线短信应用

我搜索了很多但一无所获。请帮助我如何解决这个问题。

收件箱活动

class InBox : AppCompatActivity() {


    private val requestContactSms: Int = 3
    private val requestReceiveSms: Int = 1
    private val requestReadSms: Int = 2

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

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.SEND_SMS) !=
            PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this, arrayOf(android.Manifest.permission.SEND_SMS, android.Manifest.permission.READ_CONTACTS),
                requestReadSms)
        } else {
            refreshSmsInbox()

        }
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) !=
            PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this, arrayOf(android.Manifest.permission.READ_CONTACTS),
                requestContactSms
            )
        } else {
            refreshSmsInbox()

        }
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.RECEIVE_SMS) !=
            PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this, arrayOf(android.Manifest.permission.RECEIVE_SMS, android.Manifest.permission.READ_CONTACTS),
                requestReceiveSms
            )
        }

    }


    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == requestReadSms && requestCode == requestContactSms) refreshSmsInbox()
    }

    @SuppressLint("Recycle", "SimpleDateFormat")
    private fun refreshSmsInbox() {
        try {


            val smsList = ArrayList<SmsData>()
            val cursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null)
            cursor?.let {
                if (it!!.moveToFirst()) {

                    val nameID = it.getColumnIndex("address")
                    val messageID = it.getColumnIndex("body")
                    val dateID = it.getColumnIndex("date")
                    val parser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss") //Input date formate
                    val formatter = SimpleDateFormat("HH:mm a") //Output date formate
                    val formattedDate = formatter.format(parser.parse("2018-12-14T09:55:00"))
                    do {
                        val dateString = it.getString(dateID)
                        // val sms = SmsData(getContactName(this,it.getString(nameID!!.toInt()).toString()),it.getString(messageID),
                        //SimpleDateFormat("hh:mm a").format(Date(dateString.toLong()).toString())
                        val sms = SmsData(getContactName(this,it.getString(nameID!!.toInt()).toString()),it.getString(messageID),
                            SimpleDateFormat("hh:mm a").format(Date(dateString.toLong()).toString())
                        )
                        smsList.add(sms)
                    } while (it.moveToNext())

                    it.close()
                }
                val adapter = ListAdapter(this, smsList)
                sms_list_view.adapter = adapter
            }
        }catch (ex: Exception){
            if (this != null){
                Toast.makeText(this,ex.localizedMessage, Toast.LENGTH_SHORT).show()
            }
        }

    }
        @SuppressLint("Recycle")
        fun getContactName(context: Context, phoneNumber: String): String? {
            var contactName: String = phoneNumber
            val uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber))
            val cursor = context.contentResolver.query(uri, arrayOf(ContactsContract.PhoneLookup.DISPLAY_NAME), null, null, null)
            cursor?.let {
                if (it.moveToFirst()) {
                    contactName = it.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME))
                }
                it.close()
            }
            Log.d("Inbox","contactName $contactName for $phoneNumber")
            return contactName;
        }

}

列表适配器类

class ListAdapter (val context: Context, val list : ArrayList<SmsData>): BaseAdapter(){
    @SuppressLint("ViewHolder", "SimpleDateFormat")
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view = LayoutInflater.from(context).inflate(R.layout.rowlayout,parent,false)

        list[position].senderName?.let{
            view.sender.text = it.substring(0,1).toUpperCase()
        }

        view.sms_sender.text = list[position].senderName

        view.sms_message.text = list[position].message

        val date: Date = Date(list[position].date)
        val dateFormat = SimpleDateFormat("hh:mm a")
        view.sms_date.text = dateFormat.format(date)

        return  view
    }

    override fun getItem(position: Int): Any {
        return list[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getCount(): Int {
       return list.size
    }
}

对话活动

private const val TAG = "MainActivity1"

class MainActivity1 :AppCompatActivity(){

    private val requestReceiveSms: Int = 1
    private val requestSendSms: Int = 2
    private var mMessageRecycler: RecyclerView? = null
    private var mMessageAdapter: MessageAdapter? = null

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

          seupRecycler()



        btnSend.setOnClickListener {

            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.SEND_SMS) !=
                PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this, arrayOf(android.Manifest.permission.SEND_SMS),
                    requestSendSms
                )
            } else {
                SendSms()
            }
        }

        if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.RECEIVE_SMS) !=
            PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.RECEIVE_SMS),
                requestReceiveSms)
        }
    }

    private fun seupRecycler() {
        mMessageRecycler = this.reyclerview_message_list as RecyclerView
        mMessageAdapter = MessageAdapter(this)
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.VERTICAL
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
                                                grantResults: IntArray) {
            if(requestCode == requestSendSms)SendSms()
        }

        private fun SendSms() {

            val str_addtes = address.text.toString();
            val str_message = txtMessage.text.toString();

            SmsManager.getDefault().sendTextMessage(str_addtes,null,str_message,null,null)

            Toast.makeText(this,"SMS Sent",Toast.LENGTH_SHORT).show()



        }
}

收件箱 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <ListView

            android:id="@+id/sms_list_view"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="6"
            tools:ignore="Suspicious0dp"/>


</LinearLayout>

单触点布局 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="horizontal"
              android:padding="10dp">

    <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/sender"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_gravity="center"
            android:gravity="center"
            android:layout_marginRight="16dp"
            android:background="@drawable/circle"
            android:textColor="#F5F0F1"
            android:textSize="30sp" />

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="match_parent"
                  android:id="@+id/click"
                  android:layout_height="wrap_content"
                  android:orientation="vertical">

        <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/sms_sender"

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="16sp" />

        <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/sms_message"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:textSize="16sp" />

        <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/sms_date"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="10sp" />
    </LinearLayout>
</LinearLayout>

Android 清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools" package="com.msgPractice.practice">
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.WRITE_CONTACTS"/>
        <uses-permission android:name="android.permission.SEND_SMS"/>
        <uses-permission android:name="android.permission.READ_SMS"/>
        <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme" tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".InBox">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".MainActivity1"></activity>

        <receiver android:name=".SmsReceiver"
                  android:enabled="true"
                  android:exported="true" android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="1000">
                <action android:name = "android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>

        </receiver>
    </application>

</manifest>

预期的:

当用户单击收件箱选项卡中的任何消息时,移动到对话选项卡。

实际的:

单击时没有任何反应。

标签: androidandroid-layoutandroid-activitykotlin

解决方案


您需要在适配器类中调用 startActivity

class ListAdapter (val context: Context, val list : ArrayList<SmsData>): BaseAdapter(){
@SuppressLint("ViewHolder", "SimpleDateFormat")
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    val view = LayoutInflater.from(context).inflate(R.layout.rowlayout,parent,false)

    list[position].senderName?.let{
        view.sender.text = it.substring(0,1).toUpperCase()
    }

    view.sms_sender.text = list[position].senderName

    view.sms_message.text = list[position].message

    val date: Date = Date(list[position].date)
    val dateFormat = SimpleDateFormat("hh:mm a")
    view.sms_date.text = dateFormat.format(date)
    view.clickListener { View -> 
        val intent = MainActivity1.newIntent(context, MainActivity1.class)
        context.startActivity(intent)
    }       
    return  view
}

override fun getItem(position: Int): Any {
    return list[position]
}

override fun getItemId(position: Int): Long {
    return position.toLong()
}

override fun getCount(): Int {
   return list.size
}}

推荐阅读