根据列表视图对象位置按ID选择文本

本文关键字:ID 选择 文本 位置 对象 列表 视图 | 更新日期: 2023-09-27 18:21:35

Edit:这是针对C#的,而不是Java。

我觉得这应该没有那么难,但我已经为此挣扎了好几个小时,希望有人能帮我解决这个问题。

基本上,我有一个列表视图,每行都有5个文本视图。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
  <TextView
      android:id="@+id/id"
      android:layout_height="wrap_content"
      android:layout_width="0px"
      android:layout_weight="1"
      android:text="id"/>
  <TextView
      android:id="@+id/Name"
      android:layout_height="wrap_content"
      android:layout_width="0px"
      android:layout_weight="1"
      android:text="Name" />
  <TextView
    android:id="@+id/Status"
    android:layout_height="wrap_content"
    android:layout_width="0px"
    android:layout_weight="1"
    android:text="Status" />
  <TextView
    android:id="@+id/Lat"
    android:layout_height="wrap_content"
    android:layout_width="0px"
    android:layout_weight="1"
    android:text="Lat"/>
  <TextView
   android:id="@+id/Long"
   android:layout_height="wrap_content"
   android:layout_width="0px"
   android:layout_weight="1"
   android:text="Long"/>
</LinearLayout>

所以我想要的是,当有人点击该行时,我可以从该特定行中的任何子文本视图中获取文本。

所以我可以使用e.position在列表视图中获取位置,或者使用获取对象

    ListView listView = FindViewById<ListView>(Resource.Id.LocationsList);
    var item = listView.GetChildAt(e.Position);

但是,我怎样才能获得该对象中的5个文本视图呢?

非常感谢你的帮助!

根据列表视图对象位置按ID选择文本

这是C#版本的

listView.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) => {
    var textView1 = e.View.FindViewById(Resource.Id.textview1);
    var textView2 = e.View.FindViewById(Resource.Id.textview2);
};

或者,如果你已经有了这个职位,你可以使用

ListView listView = FindViewById<ListView>(Resource.Id.LocationsList);
var item = listView.GetChildAt(e.Position);
var textView1 = item.FindViewById(Resource.Id.textview1);

正确的方法是使用OnItemClickListener:

 listView.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView nameView = (TextView) view.findViewById(R.id.Name);
      }
    });

ListView OnItemClickListener

ListView listView = (ListView)findViewById(R.id.LocationsList);
lv.setOnItemClickListener(new OnItemClickListener()
{
    @Override 
    public void onItemClick(AdapterView<?> arg0, View ItemView,int position, long arg3)
    { 
        // ItemView is the view of the list item that was clicked
        // since u said there will be 5 text views i.e. fixed number of text views below code seemb to be reasonable.
        // if the number of text is varying then better approach would be to get all the child nodes and proceed
        TextView txt1 = (TextView )findViewById(R.id.TextView1);
        ...
        ...
        TextView txt5 = (TextView )findViewById(R.id.TextView5);
    }
});