为什么吐司显示总是10?

时间:2014-02-05 18:33:30

标签: android

这是我的代码:

        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.container);
    for (i=0;i<10;i++) {
        webView = new WebView(this);
        webView.setId(i);
        webView.getSettings().setJavaScriptEnabled(true);
        String customHtml = "<p>WebView ID: <b>"+i+"</b></p>";
        webView.loadData(customHtml, "text/html", "UTF-8");
        webView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Toast.makeText(getApplicationContext(),"i: "+i,Toast.LENGTH_SHORT).show();
                return false;
            }
        });
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        lp.bottomMargin += 5;
        linearLayout.addView(webView, lp);
    }

我想在toast上显示webview id,但它总是显示10个。

请帮助解决此问题。

2 个答案:

答案 0 :(得分:2)

更改为:

Toast.makeText(getApplicationContext(),"i: "+view.getId(),Toast.LENGTH_SHORT).show();

当循环点击事件完成时,我的最后一个值为10。

或做:

 for (int i=0;i<10;i++) {
            final int x=i;
            webView = new WebView(this);
            webView.setId(i);
            webView.getSettings().setJavaScriptEnabled(true);
            String customHtml = "<p>WebView ID: <b>"+i+"</b></p>";
            webView.loadData(customHtml, "text/html", "UTF-8");
            webView.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    Toast.makeText(getApplicationContext(),"i: "+x,Toast.LENGTH_SHORT).show();
                    return false;
                }
            });
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
            lp.bottomMargin += 5;
            linearLayout.addView(webView, lp);
        }

答案 1 :(得分:0)

当您使用i作为网络视图的id时,最简单的更改就是:

Toast.makeText(..., "i: " + view.getId(), ...).show();