[英]Cannot instantiate custom class in android Activity layout XML file
[英]About XML layout & custom android class
我正在使用Eclipse IDE。 我應該如何定義在activity_main.xml
初始化的類(例如)? 假設,在activity_main.xml
我具有ListView對象的定義,例如:
<ListView
android:id="@+id/ListViewAction"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
</ListView>
通常,我可以在MainActivity.java
文件中進行處理,這很好。
但是我想將代碼拆分到不同的.java
文件,並創建擴展ListView的類。 因此,我創建了一個新的Java類文件,並且應該在該類中放置什么以使ListView重載? 如果我將標准類定義放在該新的Java文件中,將無法使用:
public class ListViewAction extends ListView {
public ListViewAction(Context context) {
super(context);
System.out.println("ListViewAction()");
}
}
如何在新的Java文件和XML中正確定義類?
如果要自定義自己的ListView
,則必須執行以下操作:
public class myOwnListView extends ListView {
final Context context;
public myOwnListView(Context context) {
super(context);
this.context = context;
}
public myOwnListView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public myOwnListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
}
}
// instead of
<ListView
android:id="@+id/ListViewAction"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
// you need to do as below
<com.my.package.name.myOwnListView
android:id="@+id/ListViewAction"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
public class MainActivity extends Activity {
// initialize your ListView:
myOwnListView myListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// find your view in your layout:
listview = (myOwnListView) findViewById(R.id.ListViewAction);
// set to an adapter...
listview.setAdapter( [...] );
// more stuff
}
}
在布局中,嘗試始終使用match_parent
/ fill_parent
將小部件的高度設置為GridView
或ListView
為其父布局的高度。
使用tokou的HeaderListView這個項目或Sergey Burish的這個HFGridView 項目 ,您可以看到它是如何工作的,並且您將擁有一種最佳方法來完成您想要的事情。
希望這會有所幫助。
如果添加了MyListView
:
package my.app;
public class MyListView extends ListView {
// ...
}
您可以使用完整的類名在XML中引用它:
<my.app.MyListView
...
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.