Android - ListView布局两行列表项

时间:2016-07-29 19:47:48

标签: android listview textview onitemclicklistener

我有一个listview,其中包含两行项:用户ID和用户名。如何在单击其中一行时从listview检索用户ID?

public class MainActivity extends AppCompatActivity {

private DatabaseReference mUsers;
String getValue = null;
ListView lvUsers = (ListView) findViewById(R.id.lvUsers);

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    mUsers = FirebaseDatabase.getInstance.getReference().child(Constants.FIREBASE_USERS);

    FirebaseListAdapter<Users> adapter = new FirebaseListAdapter<Users>(
            this, Users.class, android.R.layout.two_line_list_item, mUsers
    ) {
            @Override
            protected void populateView(View v, Users user, int pos) {
            ((TextView)v.findViewById(android.R.id.text1)).setText(user.getUserID());
            ((TextView)v.findViewById(android.R.id.text2)).setText(user.getUsername());
            }
    };

    lvUsers.setAdapter(adapter);
    setupListViewMenu(); 
}

private void setupListViewMenu() {
    lvUsers.setOnItemLongClickListener(
            new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapter,
                                       View item, int pos, long id) {

            // How to retrieve only User ID from here?
            getValue = ((TextView)view).getText().toString();

            return true;
        }

    });
}
}

listview数据来自Firebase数据库。是使用for loop检索的唯一方法吗?我必须循环二维数组?感谢

1 个答案:

答案 0 :(得分:1)

你可以试试下面的代码吗?

getValue = ((TextView)item.findViewById(android.R.id.text2)).getText().toString();

我认为android.R.id.text2item(在clickListener中收到View)的孩子之一

但需要测试......希望它有效