Question

I have a linearlayout, which contains my TextView I want access. In this linearlayout there is a listview, where every item is a linearlayout and contains also custom views.

Deep in there is a button with an onclickListener. After performing onClick(), I want to call a method which sets the text of my textview. At the moment I am doing it like this:

(View)this.getParent().getParent().getParent().getParent().getParent().getParent().getParent().findViewById(R......)

It works, but it looks bad. Is there any possibility to do it a better way?

Image

Was it helpful?

Solution

Yes, its ugly, don't do that.

In your onClick(View v) get hold of TextView by asking Activity holding the layout:

@Override
public void onClick(View v) {
    TextView tv = (TextView) YourActivity.this
        .findViewById(R.id.your_text_view_id);
    tv.setText("blabla");
}

if you do it from fragment instead of activity use :

YourFragment.this.getView().findViewById(R.id.your_text_view_id) 

Or simply create a member TextView mTv, initialize it in your #OnCreate and use it everywhere as suggested in comments to your question

OTHER TIPS

It looks bad, because it is generally a bad idea for a view to know something about outside of it self. So it is probably okay to know about your children but not back.

You'd better keep your views as simple as views, without any other logic. Do your logic in Activities/Fragments

See Circular dependency

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top