将值传递给Java中的函数

时间:2014-02-20 08:46:47

标签: java android sharedpreferences

我正在使用android studio构建一个Android应用程序。我有一个作为共享偏好存储的证人列表,当使用点击修改这些证人被分割并列出用户可以点击他们想要修改的证人,那就是计划,我只是似乎无法通过证人列出的号码(基本上是循环中使用的数字)到另一个函数,它将证人信息加载到要修改的表格中。以下是我的代码:

            String s= WitnessDetails;
            String[] array = s.split("$_$(?=[0-9])");   

            LinearLayout parentLayout = (LinearLayout)findViewById(R.id.LinearLayout);
            // Layout inflater
            LayoutInflater layoutInflater = getLayoutInflater();
            View view;

        for(String str : array)
        {
            countWitness++;
            String WitnessName= str;

            view = layoutInflater.inflate(R.layout.witnesses_activity, parentLayout, false);

            // In order to get the view we have to use the new view with text_layout in it
            TextView textView = (TextView)view.findViewById(R.id.Witnesses_details);
            textView.setText("Witness 1: " + countWitness + "\n" + WitnessName+"\n Edit");

            // Add the text view to the parent layout
            parentLayout.addView(textView);

            textView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View arg0) {                      
                    Amendwitness(countWitness);
                }
            });

          }

          public void Amendwitness(witnessNum){

          }

2 个答案:

答案 0 :(得分:2)

您在 内部匿名类 中使用countWitness,所以

countWitness应为final

countWitness应为 类字段

否则编译器将显示错误。由于countWitness在for循环中递增,因此无法将其声明为final,因此唯一的解决方案是将其作为class-field


OR

您可以使用setTag(Object)功能

    for(String str : array)
    {
        countWitness++;
        String WitnessName= str;

        view = layoutInflater.inflate(R.layout.witnesses_activity, parentLayout, false);

        TextView textView = (TextView)view.findViewById(R.id.Witnesses_details);
        textView.setText("Witness 1: " + countWitness + "\n" + WitnessName+"\n Edit");
        textView.setTag(countWitness); // set the countWitness as tag object

        parentLayout.addView(textView);

        textView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {                      
                Amendwitness((Integer)arg0.getTag());
            }
        });

      }

答案 1 :(得分:0)

以下是两种可能性:

  1. 添加自定义MyClickListener类:

    public class MyClickListener implements View.OnClickListener {
        private int mIndex;
    
        public MyClickListener(int index) {
            mIndex = index;
        }
    
        @Override 
        public void onClick(View v) {
            Amendwitness(index);
        }
    }
    

    像这样添加OnClickListeners

    textView.setOnClickListener(new MyClickListener(countWitness));
    
  2. 使用视图的标记:

    textView.setTag(countWitness);
    textView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {                      
            Amendwitness(v.getTag());
        }
    });