【问题标题】:Showing a custom View on a list item view在列表项视图上显示自定义视图
【发布时间】:2014-03-27 02:14:38
【问题描述】:

这可能看起来很奇怪,但我正在尝试显示我在列表视图项上创建的自定义视图。 我的自定义视图绘制键盘和弦,当我在 FragmentActivity 上显示它们时,这个工作, ViewPager 等我像以前一样,创建了一个 XML 文件作为列表项并实现了一个类 从 ArrayAdapter 扩展。当我对 XML 文件进行膨胀时,它可以正常工作,但无法正常工作 当我使用我的自定义视图类时,它没有 xml 文件。你们有什么线索吗?我的代码如下。非常感谢:)

public class ShowChordActivityNew extends Activity {

    private ListView chordList;

    private List<KeyboardChordDiagram> aList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_chord_activity_new);

        chordList = (ListView) findViewById(R.id.lvChords);
        // this array is a chord I'm using to test this before moving to my working code
        int[] chord = new int[] { 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        aList = new ArrayList<KeyboardChordDiagram>();      
        aList.add(new KeyboardChordDiagram(getApplicationContext(), "A", chord));
        aList.add(new KeyboardChordDiagram(getApplicationContext(), "A", chord));
        aList.add(new KeyboardChordDiagram(getApplicationContext(), "A", chord));


        chordList.setAdapter(new MyAdpater());  
    }

    private class MyAdpater extends ArrayAdapter<KeyboardChordDiagram> {

        public MyAdpater() {
            super(getApplicationContext(), R.layout.fragment_list_item, aList);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            if (itemView == null) {
                //since my class extends View, this should work, right?
                KeyboardChordDiagram a = aList.get(position);       
                itemView = a;                   
            }

            return itemView;
        }

    }
}

//这是我的 KeyboardChordDiagram 类构造函数 公共类 KeyboardChordDiagram 扩展 ChordDiagram { .....

public KeyboardChordDiagram(Context context, String aChordName, int[] aChord) {
    super(context, aChordName);
    chord = aChord;
    .....
}

....

}

//这是ChordDiagram类:

公共抽象类 ChordDiagram 扩展 View 实现 OnClickListener{

.....

public ChordDiagram(Context context, String aChordName) {
    super(context);
    .....
}
....

}

【问题讨论】:

  • 请显示KeyboardChordDiagram 类,或至少显示它的构造函数。您应该在getView 函数中创建新的KeyboardChordDiagram。您的问题是您没有与列表建立和弦的父/子关系。
  • 我编辑了问题以添加构造函数。我正在努力理解我应该如何将和弦与列表绑定。我试图在 getView() 方法中实例化一个 KeyboardChordDiagram,将 getContext() 作为参数传递,但它不起作用:(

标签: android android-listview android-custom-view


【解决方案1】:

您还没有将值绑定到放置在您的 itemView 中的视图。我认为您需要将“a”对象中的值绑定到列表视图行。这在 getView 中没有

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多