将事件处理程序分配给循环中具有变量的对象

时间:2014-11-06 11:26:09

标签: java android events

我无法以编程方式向表行添加事件处理程序。由于我必须将变量声明为final,因此所有事件处理程序始终只使用最后指定的值。我不知道如何解决这个问题。有没有人有任何想法?

    public void Refresh()
{
    Looper.prepare();
    final Context context = getApplicationContext();
    CharSequence text = "Refreshen...";
    int duration = Toast.LENGTH_SHORT;

    try {
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(new HttpGet("http://www.nu.nl/"));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            String responseString = out.toString();
            String[] lines = responseString.split("\n");
            for(int i = 0; i < lines.length; i++)
            {
                if(lines[i].contains("<li class=\"  \" data-vr-contentbox=\"articlelist"))
                {
                    final String url = stripSpaces(lines[i + 2].replace("<a href=\"", "").replace("\" class=\"trackevent\" >", ""));
                    final String title = stripSpaces(lines[i + 6].replace("<span class=\"title\">", "").replace("</span>", ""));
                    final TableLayout tl = (TableLayout) findViewById(R.id.table);
                    activity.runOnUiThread(new Runnable() {
                        public void run() {
                            TableRow row = new TableRow(context);
                            row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
                            TextView view = new TextView(context);
                            view.setText(title);
                            row.addView(view);
                            tl.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent(activity, News.class);
                                    intent.putExtra("url", url);
                                    startActivity(intent);
                                }
                            });
                            tl.addView(row, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
                        }
                    });
                }
            }
        } else {
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    }

1 个答案:

答案 0 :(得分:0)

最后想通了,结果我把onClick事件设置为整个表而不是行......