for循环中的OnClickListener

时间:2015-11-03 02:53:58

标签: android for-loop indexoutofboundsexception

我得到一个"错误:(99,95)错误:从内部类中访问局部变量i;需要被宣布为最终的#34;试图使用" i"来自OnClick方法中For循环的变量 我试着把这个"我"在一个全局变量中然后我得到一个" ArrayIndexOutOfBoundsException"。
 但我不能以另一种方式思考。

    private void createTextViews(TextView[] textViewArray, LinearLayout linearLayout){
    for (int i = 0; i < keys.length; i++) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(20, 0, 0, 20);

        TextView newView = new TextView(getActivity());
        newView.setLayoutParams(layoutParams);
        newView.setText("Watch the Trailer " + (i + 1));
        newView.setTextSize(22);
        newView.setTextColor(getResources().getColor(R.color.words));
        newView.setBackgroundColor(getResources().getColor(R.color.button));
        newView.setHighlightColor(getResources().getColor(R.color.background));
        newView.setPadding(5, 5, 5, 5);
        newView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(YOUTUBE_URL+keys[i]));
                startActivity(intent);
            }
        });

        linearLayout.addView(newView);
        textViewArray[i] = newView;
    }
}


我怎样才能做到这一点?
--------------
编辑
这是ArrayIndexOutOfBoundsExeption的日志:

11-03 01:08:13.866  32159-32159/app.com.example.android.popularmovies E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: app.com.example.android.popularmovies, PID: 32159
java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
        at app.com.example.android.popularmovies.Detail_ActivityFragment$1.onClick(Detail_ActivityFragment.java:99)
        at android.view.View.performClick(View.java:4456)
        at android.view.View$PerformClick.run(View.java:18465)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5086)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

你得到越界异常的原因是因为在最后一个循环中你虽然没有再次进入循环,但是你是一个类变量的i现在已经超出了界限。因此,将i作为类变量的整个方法在您的情况下不起作用。

实现此目的的一种方法是将i实际保存在视图中的标记中,然后从单击的视图中读取该标记。

newView.setTag(i)

然后在onClick

v.getTag() 
上面的

可以用来获取i

答案 1 :(得分:1)

你必须初始化新的最终int值

添加final int ex = i;

在setOnClickListener之前

并且不要忘记改变

Uri.parse(YOUTUBE_URL + keys[i]));

Uri.parse(YOUTUBE_URL + keys[ex]));