Android,自定义视图中的UI元素

Android,自定义视图中的UI元素,android,android-view,ondraw,Android,Android View,Ondraw,我已经习惯在android中创建自定义视图。我希望做的一件事是在自定义视图中包括现有的UI元素,如EditText,或Switch 我以前使用Cocoa(iOS)开发过,能够在自定义视图中实例化本机元素 在我的视图的onDraw(画布),我有: edit = new EditText(getContext()); edit.setDrawingCacheEnabled(true); Bitmap b = edit.getDrawingCache(); canvas.drawBitmap(b,

我已经习惯在android中创建自定义视图。我希望做的一件事是在自定义视图中包括现有的UI元素,如
EditText
,或
Switch

我以前使用Cocoa(iOS)开发过,能够在自定义视图中实例化本机元素

在我的视图的
onDraw(画布)
,我有:

edit = new EditText(getContext());

edit.setDrawingCacheEnabled(true);
Bitmap b = edit.getDrawingCache();

canvas.drawBitmap(b, 10, 10, paintDoodle);
当我执行时,应用程序在显示之前崩溃。我这样做是错误的,还是在java中不可能合并本机元素

日志:

java.lang.NullPointerException
            at android.view.GLES20Canvas.drawBitmap(GLES20Canvas.java:739)
            at android.view.GLES20RecordingCanvas.drawBitmap(GLES20RecordingCanvas.java:91)
在java中不可能合并本机元素吗

不,这是可能的

以下是以编程方式创建EditText的方法,例如:

LinearLayout layout = (LinearLayout) view.findViewById(R.id.linearLayout);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);

EditText editText= new EditText(this);
editText.setLayoutParams(params);
layout.addView(editText);

如果您发布自定义视图的代码,我可能会为您提供更多帮助。

很有可能合并本机元素,我每天都这样做,但您做得非常错误。您不直接绘制它们,只有在真正进行自定义绘制时才直接绘制,如果您希望在CustomView中包含现有视图,则将该视图添加到CustomView中

另外,不要在
onDraw
方法中分配
new
对象

我将举一个我认为最干净的方法的例子。

public class MyCustomWidget extends LinearLayout {

  // put all the default constructors and make them call `init`

  private void init() {
      setOrientation(VERTICAL);
      LayoutInflater.from(getContext()).inflate(R.layout.custom_widget, this, true);
      // now all the elements from `R.layout.custom_widget` is inside this `MyCustomWidget`

     // you can find all of them with `findViewById(int)`
     e = (EditText) findViewById(R.id.edit);
     title = (TextView) findViewById(R.id.title);

     // then you can configure what u need on those elements
     e.addTextChangedListener(this);
     title.setText(...some value);
  }
  EditText e;
  TextView title;

}
当然,您可以从中推断出更复杂的内容,例如,您有一个
User
对象,并且您的
MyCustomWidget
位于适配器中,您可以添加一个方法:

public void setUser(User user) {
    title.setText(user.getName());
}

你能把你的航海日志寄出去吗?