Pergunta

I am actually developing an android application which needs to inflates many times the same XML layout.

This layout contains 2 buttons, some textViews and a progressBar which I'll need to update later. I would like to add onClick listeners to the buttons and to set custom tags with setTag() to all of these elements, so I will be able to know which button has been clicked and to modify the right textView (or progressBar).

I inflate the XML with this code :

LinearLayout countersList = (LinearLayout)findViewById(R.id.countersLayout);
View child = getLayoutInflater().inflate(R.layout.counter, null);
countersList.addView(child);

How can I access to the right view to set the tag and to add listeners? Is there a better way to do what I want to do ?

Thank you very much !

Foi útil?

Solução

As far as how to tag or add onClick listeners to your views: You can add an ID to the views you want to tag and find them using findViewById. For example,

LinearLayout countersList = (LinearLayout)findViewById(R.id.countersLayout);
ViewGroup child = (ViewGroup) getLayoutInflater().inflate(R.layout.counter, null);
child.findViewById(R.id.myButton).setTag("myTagForTheButton");
countersList.addView(child);

On the second question, I'm not sure what your UI looks like, but many repeated views might call for using a ListView.

Outras dicas

There is no problem of setting tags and listener

LinearLayout countersList = (LinearLayout)findViewById(R.id.countersLayout);
View child = getLayoutInflater().inflate(R.layout.counter, null);
child.setTag("YourString");
// Similarly
view.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
            }
        });
countersList.addView(child);

If you want it for some of its child you can also do it using findViewById

you can user view.setTag(key, tag) to many tags. ex: view.setTag("right_view", rightView);

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top