views:

26

answers:

2

I would like to ask if there is any methods to get a View from another View.

My case is that: I have a custom ImageView call MyImageView. and my layout is that:

FrameLayout:
  MyImageView 
  LiearLayout:
      LiearLayout: 
          TextView 
      LiearLayout:
          TextView

I have some code in MyImageView and I would like to edit the text in TextView under the LinearLayout.

my code in MyImageView for select the TextView is:

TextView textView = (TextView) findViewById(id.TextView01);

However textView is always null and I can't set the text that I prefered.

More, if I code this:

TextView textView = (TextView) findViewById(R.id.TextView01);

Eclipse will give me a error and said can;t resolve the id.

So Is there any methods to edit TextView from a ImageView?

A: 

First of all... that's a horrible idea (I would be freaked out if I were you). And it's big signal that you have to rethink how to do your layout.

Anyway, using the getParent method could work:

// in your MyImageView
FrameLayout parent = (FrameLayout)getParent();
TextView textView = (TextView) parent.findViewById(R.id.TextView01);

It's not working the way you are doing it, since the TextViews are not inside your custom view.

Cristian
Thanks. It works.Actually, I something doubt that, whether the touch event should be implement in the view or activity. This time I choose implement in the View. So the problem came out! :(
eRIcYang
A: 

I think you can always call getRootView() and from there you can search for a view by Id. As long as the ids are unique within the current view hierarchy you should be able to grab the textView no matter where it is in the hierarchy.

So similar to the other answer

TextView textView = (TextView) getRootView().findViewById(R.id.textview_01);

if it's on the same screen, it will be there always.

Greg
THX... The problem has solved.
eRIcYang