How to add onclicklistener to dynamically generate

2019-01-26 08:38发布

In my application generating dynamic text view. I want to add onclickListener to my text view. How can I do it please give me some hint. Here hard code for textview .

        for (int i = 0; i < subCategory.length; i++) {
        TextView tv = new TextView(this);
        tv.setText(subCategory[i]);
        tv.setId(i);
        sCategoryLayout.addView(tv);

    }

9条回答
Ridiculous、
2楼-- · 2019-01-26 09:22

Create one View.onClickListener() object "mListener". Add this object to tv.setOnClickListener(mListener) in for loop.

查看更多
smile是对你的礼貌
3楼-- · 2019-01-26 09:26
for (int i = 0; i < subCategory.length; i++) {
        TextView tv = new TextView(this);
        tv.setText(subCategory[i]);
        tv.setId(i);
        tv.setOnClickListener(this);
        sCategoryLayout.addView(tv);

    }

@Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
     switch(v.getId())
     {
     case 1:
     //Write Code For Click Here
     break;
     default:
     break;
    }
}

Impelement OnClickListner on this class.

查看更多
【Aperson】
4楼-- · 2019-01-26 09:29

Yes I have also getting the same problem but friend I got the solution and it's worked for me

I have added Textview in run time and also get them click below is code.

for (int i = 0; i < albumItemList.size(); i++) {
       toplayout = getActivity().getLayoutInflater().inflate(R.layout.addphotoalbumlistinfater, null);
       newTV = (TextView)toplayout.findViewById(R.id.textView) ;
       textViewcount= (TextView)toplayout.findViewById(R.id.textViewcount) ;
       ll = (RelativeLayout) toplayout.findViewById(R.id.mainitemlist) ;
       ll.setTag("position"+i);
       newTV.setText(albumItemList.get(i).getAlbumName());
       textViewcount.setText(""+albumItemList.get(i).getCount());
       ll.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
          Toast.makeText(getActivity(),""+v.getTag(),Toast.LENGTH_SHORT).show();
           }
         });
       linearLayoutforaddchild.addView(toplayout);
     }
查看更多
登录 后发表回答