java - 关于 XML 布局和自定义 android 类

标签 java android android-xml

我正在使用 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,你必须做这些事情:

1 。使用小部件扩展新类并附加上下文:

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;
    }
}  

2。更改布局的 ListView:

// 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" />  

3 。在你的 onCreate 方法中使用它:

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
    }

}

4 。避免一些错误:

在您的布局中,尝试始终将小部件的高度设置为 GridViewListView 使用 match_parent 的父布局的高度/fill_parent


有了这个项目 HeaderListView tokou 或这一个 HFGridView Sergey Burish 编写,您可以看到它是如何工作的,并且您将有一个最好的方法来做您想做的事。
希望这会有所帮助。

关于java - 关于 XML 布局和自定义 android 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22146826/

相关文章:

java - 计算指数增长系列中的值之和

java - 在 MySQL 中添加 NullPointerException

java - 选择菜单验证错误 : Value is not valid

android - 不要在 appwidget 的 gridview 中的 imageview 中显示图像

android - RecyclerView 不是真正的 wrap_content 在 ScrollView

android - 我怎样才能给我的 EditTexts 一个更亮的背景?

java - 如何在我的自定义控件中实现类似 JLabel 的大小管理?

具有主要 Activity 的 Android 抽屉布局

android - 在 Android 中实现 MVC 的好处

android - 如何将旋转的布局右对齐并匹配父级高度?