我应该用什么来查找动态创建的TextView

时间:2017-10-30 10:16:36

标签: android tablerow

我必须问你如何找到我的视图,我是动态创建它们的,因为有关文本的所有信息都在我的字符串数组中,现在我想找到它来通过getter将它存储在Class中,以便在另一个类,在功能上我想要后端存储信息,这就是为什么我选择类来进行临时解决方案。

这就是我的代码

sportlist = getResources().getStringArray(R.array.btnsport);
    for(j=0;j<sportlist.length;j++){
        sporthash.put(j,sportlist[j]);
        System.out.println(sporthash);
    }


//Here I create my TableRow with TextView

    TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT);
    lp.height = 120;
    lp.setMargins(8,8,8,8);

    for(j=0;j<sportlist.length;j++) {
        TableRow row = new TableRow(getActivity());
        row.setLayoutParams(lp);
        final TextView t = new TextView(getActivity());
        t.setPadding(10, 10, 10, 10);
        t.setText(sporthash.get(j));
        t.setGravity(Gravity.CENTER);
        t.setClickable(true);
        t.setTextSize(18);
        t.setId(j);
        t.setBackgroundResource(R.drawable.sport_false);
        t.setTextColor(Color.BLACK);

然后我有了保存按钮,它将信息发送到我的Storage.class。我尝试设置t.setId(j)并通过新的TextView h h.findViewById(j)找到它,但它的返回存储代码。我会找到t.BackgroundResource(R.drawable.sport_true)的视图并将它们发送到我的Storage.class。

这是我的按钮,因为我试图找到我的观点,那么什么解决方案最好?

 save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Storage sto = new Storage();
            sto.setAge(BirthDate.getText().toString());
            sto.setImage(civ);
            sto.setLocation(Map.getText().toString());
            System.out.println(Map.getText().toString());
            for(j=0;j<sportlist.length;j++) {



            }

            Intent newIntent = new Intent(getActivity(),ProfilActivity.class);
            startActivity(newIntent);
        }
    });

1 个答案:

答案 0 :(得分:0)

您无法在此使用setId,因为setId应与generateViewId一起使用:

来自generateViewId()的文档:

  

<强> generateViewId

     

生成适合在setId(int)中使用的值。该值不会与构建时由aapt为R.id。

生成的ID值冲突

当您尝试使用setId()设置ID时,您的ID可能会被Android Studio与自动生成的ID冲突。因此,您需要确保ID是唯一的。

您可以使用setTag()getTag()来解决setId()

的问题