2015-05-22 20 views
1

我已經習慣了在android中創建自定義視圖。我希望待辦事項之一是在我的自定義視圖中包含現有的UI元素,例如EditTextSwitchAndroid中,自定義視圖中的UI元素

我以前開發與可可(iOS),並能夠實例化自定義視圖中的本地元素。

在我的觀點中onDraw(Canvas canvas),我有:

edit = new EditText(getContext()); 

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

canvas.drawBitmap(b, 10, 10, paintDoodle); 

當我執行,應用程序崩潰之前被顯示。我是不是正確地做了這件事,或者是在java中不可能的本地元素的合併?

的logcat:

java.lang.NullPointerException 
      at android.view.GLES20Canvas.drawBitmap(GLES20Canvas.java:739) 
      at android.view.GLES20RecordingCanvas.drawBitmap(GLES20RecordingCanvas.java:91) 
+0

您可以發佈您的logcat請? – Karim

回答

1

這是非常非常有可能納入本地元素,我每天都這樣做,但你做得非常錯誤。你不直接繪製它們,如果你真的在做一個自定義繪圖,你只需要直接繪製,如果你想在你的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()); 
} 
0

是本土元素的結合不可能在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); 

如果您發佈自定義視圖的代碼,我也許能幫助你更多。

相關問題