如何从ListView获取数据和视图

时间:2013-05-18 11:08:33

标签: android listview

大家好: 我希望有人可以在这里帮助我,查询生成的Cursor使用simple_list_item_2定义的布局填充ListView。 要创建Intent,我需要单击View的第一个字符串,但在String to Go中我有类似

的内容
  

android.widget.TextView@411fbfb8

现在的代码。 我无法理解错误在哪里。

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, columns, ids, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

    final ListView myList=(ListView)findViewById(R.id.listView1);
    myList.setAdapter(adapter);
    myList.setClickable(true);

    /*
     * Click Listener
     */
    myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> l, View v, int position, long id)
        {
            Log.v("io", "start");
            Intent intent = new Intent(MainActivity.this, WorkActivity.class);

            View buff = myList.getChildAt(position);
            String toGo = buff.findViewById(android.R.id.text1).toString();

            Log.v("io",toGo);
            intent.putExtra("dname", toGo);
            startActivity(intent);
        }
    } );

4 个答案:

答案 0 :(得分:0)

尝试:

String toGo = ((TextView)buff.findViewById(android.R.id.text1)).getText().toString()

答案 1 :(得分:0)

onItemClick内,您可以通过adapter参数检索与AdapterView相关联的数据。致电getItemAtPosition(int)您可以访问与所选项目相关联的数据

myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> l, View v, int position, long id)
        {
            Log.v("io", "start");
            Intent intent = new Intent(MainActivity.this, WorkActivity.class);

            View buff = myList.getChildAt(position);
            String toGo = l.getItemAtPosition(position);

            Log.v("io",toGo);
            intent.putExtra("dname", toGo);
            startActivity(intent);
        }
    } );

答案 2 :(得分:0)

//

myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> l, View v, int position, long id)
    {
        Log.v("io", "start");
        Intent intent = new Intent(MainActivity.this, WorkActivity.class);

        //View buff = myList.getChildAt(position);
       // String toGo = buff.findViewById(android.R.id.text1).toString();
     String toGo = (TextView)v.getText();

        Log.v("io",toGo);
        intent.putExtra("dname", toGo);
        startActivity(intent);
    }
} );

答案 3 :(得分:0)

要获取视图,请执行以下操作:

LinearLayout row = (LinearLayout) ((LinearLayout)v);

RelativeLayout代替LinearLayout,如果您的情况

然后应用以下代码根据其顺序获取TextView的文本:

TextView column = (TextView)row.getChildAt(0);
String text = column.getText().toString();

希望这个帮助