【问题标题】:How can I extend spinner to implement a new function?如何扩展微调器以实现新功能?
【发布时间】:2010-12-25 01:31:23
【问题描述】:

我正在尝试在我的代码中扩展 Spinner Android 类以实现一个新功能,但由于某种原因这不起作用。

这是扩展类:

import android.content.Context;
import android.widget.AdapterView;
import android.widget.Spinner;

public class CustomSpinner extends Spinner {

    public CustomSpinner(Context context) {
        super(context);
    }

    public void setSelectionByItemId(AdapterView<?> parent, long id){
        for (int i = 0; i < parent.getCount(); i++) {              
            long itemIdAtPosition = parent.getItemIdAtPosition(i);
            if (itemIdAtPosition == id) {
                parent.setSelection(i);
                break;
            }
        }
    }
}

这就是我实例化这个类的方式:

CustomSpinner spinner = (CustomSpinner) findViewById(R.id.sphofentries);

这在运行时给我一个错误。

如果R.id.sphofentries 在我的布局中声明为微调器,所有这些都是。

但是现在,如果我将 sphofentries 声明为 CustomSpinner,我会在将 Layout 设置为 Activity 的那一刻收到运行时错误:

setContentView(R.layout.settings);

我也很确定问题是我需要将sphofentries 声明为CustomSpinner,因为如果我这样做:

CustomSpinner spinner = new CustomSpinner(this);
spinner = (CustomSpinner) findViewById(R.id.sphofentries);

这在第一行没有问题,但在第二行给出了运行时错误,然后问题不是创建一个新的CustomSpinner,而是在这个CustomSpinner 中设置sphofentries(这与sphofentries 声明类似Spinner 不是 CustomSpinner)。

也许我在布局中做错了什么,这就是我将sphofentries 声明为CustomSpinner 的方式:

<CustomSpinner 
    android:id="@+id/sphofentries"
    android:layout_below="@+id/tvhofentries"
    android:layout_width="300dip"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
/>

【问题讨论】:

  • CustomSpinner spinner = new CustomSpinner(this); spinner = (CustomSpinner) findViewById(R.id.shofentries);意味着您不了解android的工作原理。在尝试编写自己的小部件之前,我建议阅读并测试基本示例。

标签: android android-spinner


【解决方案1】:

最后有两个原因导致这个不能正常工作,前两个答案是对的:

  1. 还需要使用 AttributeSet 参数定义第二个构造函数。

    public CustomSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
    
  2. 在布局中,Spinner 必须定义为 CustomSpinner,并且需要使用所有完全限定名称声明:

    <net.domain.package.CustomSpinner  
        android:id="@+id/sphofentries" 
        android:layout_below="@+id/tvhofentries"
        android:layout_width="300dip"       
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
    />
    

【讨论】:

  • @fishjd 好的,做出改变。
  • 有没有办法避免使用完全限定名?在某处声明、导入某些东西?
【解决方案2】:

这是一个常见的错误。只需添加这个构造函数,它就是布局充气器调用的构造函数:

public CustomSpinner(Context context, AttributeSet attrs) {
    super(context, attrs);
}

【讨论】:

  • 我试过这个,但调试器甚至不能进入这个函数(不是另一个)。我将问题编辑到我所做的测试中。
【解决方案3】:

shofentries 是 Spinner 还是 CustomSpinner

需要在布局中将其声明为CustomSpinner,以便在代码中将其转换为CustomSpinner

反之亦然。您可以将CustomSpinner 转换为Spinner,因为它是一个子类。

【讨论】:

  • 我根据您的回答编辑了问题。也许我在布局中做错了什么?
  • 我之前在我的布局中做过同样的事情并且它有效,唯一的区别是我必须使用完全限定的命名空间(或包或在 java 中调用的任何东西)。尝试在布局中使用完全限定名称,看看是否会有所不同。 (即
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
  • 2019-01-29
  • 1970-01-01
  • 2011-09-25
相关资源
最近更新 更多