将editText添加到customView

时间:2013-03-02 20:59:10

标签: java android android-canvas

我想在特定坐标中将EditText添加到画布。 这样的事情:enter image description here

我尝试使用代码:

        LinearLayout layout = new LinearLayout(context);

        EditText textView = new EditText(context); 
        textView.setVisibility(View.VISIBLE);
        textView.setText("Hello world");

        layout.addView(textView);

        layout.measure(canvas.getWidth(), canvas.getHeight());
        layout.layout(0, 0, canvas.getWidth(), canvas.getHeight());
        layout.setGravity(Gravity.BOTTOM);

        layout.draw(canvas);

但是这个EditText在点击时没有显示键盘。你能救我吗?

1 个答案:

答案 0 :(得分:0)

假设你真的需要在画布上绘制......

在res / layout文件夹中创建一个新的canvaslayout.xml。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="5" >
        <requestFocus />
    </EditText>
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText1"
        android:layout_toRightOf="@+id/editText1"
        android:text="Edit Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>

也改变代码

LinearLayout layout = findViewById(R.layout.canvaslayout); 
//LinearLayout layout = youractivity.findViewById(R.layout.canvasLayout); 
layout.draw(canvas);

<强> Programmaticly:

如果您不想使用XML(我不明白为什么不这样做),您可以使用this方法。您将线性布局更改为相对布局,并使用类似的方法将视图放在另一个视图的右侧。

RelativeLayout.LayoutParams relativeLayoutParams=
            new RelativeLayout.LayoutParams((RelativeLayout.LayoutParams.WRAP_CONTENT),(RelativeLayout.LayoutParams.WRAP_CONTENT));//create params for new textview

    relativeLayoutParams.addRule(RelativeLayout.RIGHT_OF, textView.getId());//to align the textview side by side