简体   繁体   English

如何从自定义ImageView获取TextView参考?

[英]How to get TextView reference from a custom ImageView?

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. 我的情况是:我有一个自定义ImageView调用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. 我在MyImageView中有一些代码,我想在LinearLayout下的TextView中编辑文本。

my code in MyImageView for select the TextView is: 我在MyImageView中用于选择TextView的代码是:

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

However textView is always null and I can't set the text that I prefered. 但是,textView始终为null,我无法设置所需的文本。

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. Eclipse会给我一个错误,并说不能解析该ID。

So Is there any methods to edit TextView from a ImageView? 那么,有什么方法可以从ImageView编辑TextView吗?

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: 无论如何,使用getParent方法可以工作:

// 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. 由于TextViews不在您的自定义视图中,因此它无法按照您的方式进行。

I think you can always call getRootView() and from there you can search for a view by Id. 我认为您可以始终调用getRootView(),然后从那里可以通过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. 只要ID在当前视图层次结构中是唯一的,那么无论它在层次结构中的什么位置,您都应该能够获取textView。

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. 如果在同一屏幕上,它将始终存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM