Android如何检测单击了哪个tablerow

时间:2015-02-03 15:16:18

标签: android android-tablelayout clickable

在我的片段布局中,我有一个像这样的tablelayout:

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TableLayout
            android:id="@+id/tableLayout1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

        </TableLayout>
    </LinearLayout>

在这个tablelayout中,我以编程方式添加多个包含内部视图的表格,如下所示:

for(int i = 0; i < 5;){
    tableLayout.addView(createTableRow((LocationObject)objectList.get(i)), i);
}

-

private View createTableRow(LocationObject locObject) {

    TableRow tr = new TableRow(getActivity());
    View v = LayoutInflater.from(getActivity()).inflate(R.layout.view_layout, tr, false);

    TextView textViewName = (TextView) v.findViewById(R.id.textView_name);
             textViewName.setText(locObject.getTitle());

    TextView textViewProvider = (TextView) v.findViewById(R.id.textView_provider);
             textViewProvider.setText(locObject.getSubTitle());

    return v;
}

在我调用createTableRow方法几次并使用行填充tablelayout之后,我想检测用户何时单击一行。 我怎么能给行不同的id,比如第一个得到id 0,第二个等等。最后我怎么能检测到用户点击一行的时间?

编辑: 我尝试了setOnClickListener但是当我点击视图时它不起作用,“可以访问”消息从未在logcat中显示。

private View createTableRow(LocationObject locObject) {

TableRow tr = new TableRow(getActivity());
View v = LayoutInflater.from(getActivity()).inflate(R.layout.view_layout, tr, false);

...
v.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.e("output", "is reachable");
        }

    });

return v;
}

1 个答案:

答案 0 :(得分:1)

首先不要忘记i++

上的for(int i = 0; i < 5; i++)

你可以试试像:

private View createTableRow(int position) {

    //instead
    //TableRow tr = new TableRow(MainActivity.this);
    //View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.view_layout, tr, false);

    //try
    View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.view_layout, null, false);

    TextView textViewName = (TextView) v.findViewById(R.id.textView_name);
    textViewName.setText("row "+ position);

    v.setTag(position);
    v.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int position = (Integer) v.getTag();
            Log.e("output", "is reachable at position "+ position);
        }

    });

    return v;
}
单击时输出

02-04 09:36:13.615    4755-4755/noambaroz.testapplication E/output﹕ is reachable at position 0
02-04 09:36:14.680    4755-4755/noambaroz.testapplication E/output﹕ is reachable at position 2
02-04 09:36:15.310    4755-4755/noambaroz.testapplication E/output﹕ is reachable at position 4