如何在Android中以编程方式正确地将自定义视图添加到视图组?

时间:2019-05-28 05:34:52

标签: android kotlin

我正在尝试实现一个水平滚动视图,该视图基于房间数据库中的信息添加自定义的书面卡片视图。我还添加了一个文本视图,以在卡片视图中留出空间,因为在XML中配置了填充,并且以编程方式都不起作用。问题是,每当我在数据库中创建一个新的“艺术家”,然后将其添加到滚动视图时,就有可能将用于间距的文本视图添加到卡视图的不正确的一侧。另外,卡片视图有可能会重复出现,在这种情况下,根本不会添加用于间距的文本视图。

如果您需要github存储库亲自查看效果,可以在这里https://github.com/jeremyohandley/PosTattoo

对其进行克隆。

我尝试过在各个位置更改添加日志语句,并检查数据库以查看是否有重复的数据或缺少数据。我不确定错误的根源是什么。

Artist Page Fragment.kt

package com.jeremy.ohandley.postattoo

import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AlertDialog
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.jeremy.ohandley.postattoo.db.Artist
import com.jeremy.ohandley.postattoo.db.ArtistDao
import com.jeremy.ohandley.postattoo.db.Customer
import com.jeremy.ohandley.postattoo.db.database
import org.w3c.dom.Text


class ArtistPageFragment : Fragment() {

    private var db: database? = null
    private var artistDao: ArtistDao? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        db = database.getInstance(activity!!.applicationContext)
        artistDao = db!!.artistDAO()

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_artist_page, container, 
false)
    }

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

        val addArtist = view!!.findViewById<ImageButton> 
   (R.id.add_artist_button)
            addArtist.setOnClickListener { launchNewArtistDialog() }
            loadArtists()
        }

    private fun launchNewArtistDialog() {
        val inflater = LayoutInflater.from(context)
        val builder = AlertDialog.Builder(context!!)
        val builderView = 
inflater.inflate(R.layout.fragment_new_artist_dialog, null)
        initAddArtistDialogButtons(builder, builderView)

        builder.setView(builderView)
        builder.show()
    }

    private fun initAddArtistDialogButtons(builder: AlertDialog.Builder, 
builderView: View) {
        builder.setNegativeButton("Cancel") { _, _ ->
            Toast.makeText(context, "Artist not created", 
Toast.LENGTH_SHORT).show()
        }
        builder.setPositiveButton("Create Artist") { _, _ ->

            val firstNameInput = builderView.findViewById<EditText> 
   (R.id.first_name_input)
                 val lastNameInput = builderView.findViewById<EditText> 
   (R.id.last_name_input)
            val emailInput = builderView.findViewById<EditText> 
   (R.id.email_input)
            val phoneNumberInput = builderView.findViewById<EditText> 
   (R.id.phone_number_input)
            val firstName = firstNameInput.text.toString()
            val lastName = lastNameInput.text.toString()
            val email = emailInput.text.toString()
            val phoneNumber = phoneNumberInput.text.toString()

            val newArtist = Artist(null, firstName, lastName, email, 
phoneNumber)
            artistDao!!.insertArtist(newArtist)
            loadArtists()

        }


    }

    private fun loadArtists() {
        val artists = artistDao!!.getArtists()
        clearArtists()

        artists.forEach {

            val card = ArtistCard(context!!)
            val name = "${it.firstName} ${it.lastName}"
            card.setName(name)
            card.setNumber(it.phoneNumber)
            card.setEmail(it.email)
            card.setPadding(4, 4, 4, 4)
            addToLayout(card)

        }
    }

    private fun clearArtists() {
        val cardLL = view!!.findViewById<LinearLayout>(R.id.cardLL)

        for (i in 1 until cardLL.childCount) {
            cardLL.removeView(cardLL.getChildAt(i))
        }
    }

    private fun addToLayout(card: ArtistCard) {
        val spacerView = TextView(context)
        val cardLL = view!!.findViewById<LinearLayout>(R.id.cardLL)
        cardLL.addView(card)
        cardLL.addView(spacerView)
        spacerView.layoutParams = 
LinearLayout.LayoutParams(convertDpToPx(context!!, 8f).toInt(), 
LinearLayout.LayoutParams.MATCH_PARENT)

    }

    private fun convertDpToPx(context: Context, dp: Float): Float {
        return dp * context.resources.displayMetrics.density
    }



}

艺术家页面片段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"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ArtistPageFragment"
        android:orientation="horizontal"
        android:gravity="center"
        android:id="@+id/artists_linear_layout"
>

        <HorizontalScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/scroll_view"

        >
            <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal"
                    android:id="@+id/cardLL"
                    android:layoutDirection="rtl"
                    android:gravity="center"
            >


                <android.support.v7.widget.CardView
                        android:layout_width="200dp"
                        android:layout_height="300dp"
                        android:layout_margin="8dp"
                >

                    <ImageButton
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:id="@+id/add_artist_button"
                            android:src="@drawable/ic_add_24dp"
                    />

                </android.support.v7.widget.CardView>-

            </LinearLayout>

        </HorizontalScrollView>


</LinearLayout>

ArtistCard.kt(自定义卡)

package com.jeremy.ohandley.postattoo

import android.content.Context
import android.graphics.Paint
import android.support.v7.widget.CardView
import android.util.AttributeSet
import android.widget.TextView

class ArtistCard(context: Context) : CardView(context) {
    var attributes:AttributeSet? = null

    constructor(context: Context, attrs: AttributeSet) : this(context) {
        attributes = attrs
    }



    init{
        inflate(context, R.layout.artist_card, this)

        val name = findViewById<TextView>(R.id.artist_name)
        val number = findViewById<TextView>(R.id.artist_phone_number)
        val email = findViewById<TextView>(R.id.artist_email)

        val attributes = context.obtainStyledAttributes(attributes, 
R.styleable.ArtistCard)
        name.text = attributes.getString(R.styleable.ArtistCard_name)
        number.text = attributes.getString(R.styleable.ArtistCard_number)
        email.text = attributes.getString(R.styleable.ArtistCard_email)
        attributes.recycle()
    }

    fun setName (mName:String){
        val name = findViewById<TextView>(R.id.artist_name)
        name.text = mName
    }

    fun setNumber (mNumber:String){
        val number = findViewById<TextView>(R.id.artist_phone_number)
        number.text = mNumber
    }

    fun setEmail (mEmail:String){
        val email = findViewById<TextView>(R.id.artist_email)
        email.text = mEmail
    }
}

艺术家卡布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="200dp"
        android:layout_height="300dp"


>


    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center"
    >

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="Name"

        />

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:text="sample name"
                android:id="@+id/artist_name"

        />

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="Phone Number"

        />

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:text="(1)-555-555-5555"
                android:id="@+id/artist_phone_number"

        />

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="Email"

        />

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:text="sample@gmail.com"
                android:id="@+id/artist_email"

        />


    </LinearLayout>

</android.support.v7.widget.CardView>

0 个答案:

没有答案