2011-11-11 31 views
0

在我的應用程序中,我想創建一個可以作爲.java文件重用的Search部件,我需要將它反映到layout.xml文件中,以便我可以用它。直接.....這裏是我的代碼有一個編輯框,兩個按鈕。如何在Android佈局.xml中爲coustom查看java文件查看組

public class SearchWidget extends ViewGroup{ 

    Context mContext; 
    LinearLayout layout; 
    EditText edit; 
    Button searchButton; 
    Button clear; 

    LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); 

    public SearchWidget(Context context) { 
     super(context); 
     this.mContext=context; 
     layout=new LinearLayout(context); 
     edit=new EditText(context); 
     searchButton=new Button(context); 
     clear=new Button(context); 
     params.setMargins(10, 10, 10, 10); 
     layout.setOrientation(LinearLayout.HORIZONTAL); 
     layout.setLayoutParams(params); 
     edit.setMaxLines(1); 
     edit.setWidth(100); 
     layout.addView(searchButton); 
     layout.addView(clear); 
    } 

} 

請建議我如何給這個Java文件的參考我layout.xml 先謝謝了。

回答

2

您可以使用您的包名與文件名一起像

<com.myapp.SearchWidget android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
</com.myapp.SearchWidget> 

當您使用XML來把你的自定義視圖使用它,你需要使用的構造函數有兩個參數。

檢查完代碼後,會出現許多錯誤,例如最終未向搜索窗口小部件添加「佈局」。所以什麼都不會顯示出來。我不知道你的最終結果是什麼。但是,這是我認爲你正在嘗試做的事情。

public class SearchWidget extends LinearLayout { 
    public SearchWidget(Context context, AttributeSet attrs) { 
     super(context, attrs);  
      EditText edit = new EditText(context); 
     LinearLayout.LayoutParams elp = new LinearLayout.LayoutParams(0, 
      LayoutParams.WRAP_CONTENT, 1.0f); 
     edit.setLayoutParams(elp); 

     Button searchButton = new Button(context); 
     searchButton.setLayoutParams(new ViewGroup.LayoutParams(
      LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT)); 
     searchButton.setText("Search"); 

     Button clearButton = new Button(context); 
     clearButton.setLayoutParams(new ViewGroup.LayoutParams(
      LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT)); 
     clearButton.setText("Clear"); 

     addView(edit); 
     addView(searchButton); 
     addView(clearButton);  
    } 
} 

在這裏,我延長了的LinearLayout

+0

@Blessenm嗨,我得到這個,但現在我真的不能讓我的佈局屏幕則僅顯示黑屏,可以你提供任何鏈接,其中給出了完整的例子謝謝.... –

+0

我更新了我的答案 – blessenm

+0

它沒有解決問題,通過應用此......只有黑屏正在顯示/// –

0

在你的XML代碼。類名的前面添加完整的包名稱來引用,然後添加你的類名稱,如

<com.my.test.SearchWidget 
      android:id="@+id/large_photo_gallery" 
      android:layout_height="fill_parent" 
      android:layout_width="fill_parent" 
      /> 
0
package yourpackage; 
... ... 
public class SearchWidget extends ViewGroup 
{ 
    // Please use this constructor. 
    public SearchWidget(Context context, AttributeSet attrs) 
    { 
     super(context, attrs); 
    } 
    ... ... 
} 


<yourpackage.SearchWidget 
    android:id="@+id/searchWidget" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"/>