【问题标题】:Why is my custom getView Not called?为什么我的自定义 getView 没有被调用?
【发布时间】:2016-06-30 00:07:22
【问题描述】:

我不熟悉制作自定义适配器,但是我已经看到并遵循了我在网上看到的许多示例。我不知道为什么我的 getView 没有被调用。

代码如下:

private String[] numbers = new String[] {

"42", "0", "0", "39", "32", "0", "0", "0", "0", "0", "0", "0", "0", "0",
        "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "45", "0", "51",
        "36", "35", "20", "0", "22", "0", "53", "0", "1", "2", "0", "16",
        "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "5",
        "6", "0", "0", "0", "57", "0", "0", "64", "7", "0", "0", "0" };



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
//other code
grid = (GridView) findViewById(R.id.GridViewGame);
    CustomArrayAdapter adapter = new CustomArrayAdapter(this,
            R.layout.item_layout, R.id.editTextGridItem, numbers);
    grid.setAdapter(adapter);

CustomArrayAdapter 类:

public class CustomArrayAdapter extends ArrayAdapter<String> {

public CustomArrayAdapter(Context context, int resource,
        int textViewResourceId, Object[] objects) {

    super(context, resource, textViewResourceId);

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (v == null) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.item_layout, null);
    }
    else{
    v.setTag(Integer.toString(position));
    System.out.println(v.getTag());
    }
    return v;
}

总的来说,当发生这种情况时,我试图为 gridview 设置一个视图(在我的情况下,每个单元格都包含 1 个 editText),我想为该 editText 分配一个与其在数字 [] 中的位置匹配的标签。我不确定你现在的代码是否会这样做,但因为 getView 永远不会被调用

【问题讨论】:

    标签: android android-arrayadapter android-gridview


    【解决方案1】:

    您还没有将对象数组传递给父 ArrayAdapter 类,因此它认为要显示的项目为零。

    将您的构造函数更改为:

    public class CustomArrayAdapter extends ArrayAdapter<Object> {
    
        public CustomArrayAdapter(Context context, int resource,
            int textViewResourceId, Object[] objects) {
    
            super(context, resource, textViewResourceId, objects);
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = inflater.inflate(R.layout.item_layout, null);
            }
            else{
            v.setTag(Integer.toString(position));
            System.out.println(v.getTag());
            }
            return v;
        }
    }
    

    【讨论】:

    • 谢谢。这就是这个问题。构造函数缺少 this 的原因是错误。显然正确的解决方法是将对象转换为字符串 []。然而,我删除了变量,因为它是 java 给我的列表中的第一个修复。无论如何,再次感谢您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多