Android:创建自定义TextView梳理

时间:2018-03-16 07:46:05

标签: android android-layout

我正在尝试学习自定义视图。为了我创建了一个名为EditTextCarded的类,它扩展了CardView。 在init方法中,我初始化了一个EditText并为其分配了布局参数。 覆盖 onMeasure 方法并声明视图大小后, 然后通过运行我的customView,只是卡片视图出现在屏幕上,EditText不存在于CardView中或者是不可见的。发生了什么,我的textView在哪里?

class EditTextCarded @JvmOverloads
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int = 0) : CardView(context, attrs, defStyleAttr) {


    init {
        var editText = EditText(context)
        editText.layoutParams = LayoutParams(LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        editText.hint = "Test"
        addView(editText)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        ....
    }
}

我的XML布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#eee"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.groot.edittext_carded.MainActivity">

    <com.example.groot.edittext_carded.EditTextCarded
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_margin="10dp"/>

1 个答案:

答案 0 :(得分:1)

使用CardView.LayoutParams将子视图添加到CardView

public class EditTextCarded extends CardView {

private EditText editText;

public EditTextCarded(Context context) {
    super(context);
    init(context);
}

public EditTextCarded(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

public EditTextCarded(Context context, AttributeSet attrs, int 
defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
}

private void init(Context context) {
    editText = new EditText(context);
    editText.setHint("EditText");
    CardView.LayoutParams clp = new 
CardView.LayoutParams(LayoutParams.MATCH_PARENT, 
LayoutParams.MATCH_PARENT);
    addView(editText,clp);
}
}

XML

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.example.groot.edittext_carded.EditTextCarded
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</RelativeLayout>