如果点击了孩子,如何获得Listview子位置?

时间:2015-08-22 16:27:05

标签: android listview

我的应用已ListView有子女TextViewButton。 (参考图片)

enter image description here

如果单击按钮,我如何获得按钮的位置?

适配器

public class HistoryAdapter extends CursorAdapter {
public HistoryAdapter(Context context, Cursor c, int flags) {
    super(context,c, flags);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return LayoutInflater.from(context).inflate(R.layout.historylist, parent, false);
}

@Override
public void bindView(View view, final Context context, final Cursor cursor) {
    TextView text = (TextView) view.findViewById(R.id.text);
    String body = cursor.getString(cursor.getColumnIndex("name"));
    text.setText(body);
}

}

ListView onClick事件

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    setCancelable(false);
    getDialog().setTitle("History");
    View view = inflater.inflate(R.layout.history,null);
    back = (Button) view.findViewById(R.id.button);
    back.setOnClickListener(this);
    list = (ListView) view.findViewById(R.id.listView);
    ContentResolver resolver = getActivity().getContentResolver();
    c = resolver.query(Contract.SaveRunning.CONTENT_URI, null, null, null, null);
    adapter = new HistoryAdapter(getActivity(), c, 0);
    list.setAdapter(adapter);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            setChart(position);
            dismiss();
        }
    });
    return view ;
}

3 个答案:

答案 0 :(得分:1)

要获取视图,您可以按照以下方式执行此操作:

list.getChildAt(position);  //To get the view

你也可以这样做this guy does

public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

if (pos < firstListItemPosition || pos > lastListItemPosition ) {
    return listView.getAdapter().getView(pos, null, listView);
} else {
    final int childIndex = pos - firstListItemPosition;
    return listView.getChildAt(childIndex);
}

这也行得通。

答案 1 :(得分:0)

您可以在 onClick 方法中使用类似的内容来显示项目位置:

String value = lv.getItemAtPosition(position).toString();

lv 是ListView。

答案 2 :(得分:0)

我知道这个问题已经过时了,但这个问题的一个很好的解决方案是:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ixChild = ExpandableListView.getPackedPositionChild( id );
        ixGroup = ExpandableListView.getPackedPositionGroup( id );
        setChart(position);
        dismiss();
    }

这样,ixGroup包含被点击组的索引,而ixChild包含组内子进程的索引。