gpt4 book ai didi

android - 从另一个 View 而不是父 View 获取 View

转载 作者:行者123 更新时间:2023-11-29 00:26:25 26 4
gpt4 key购买 nike

我想将 2 个 View 链接在一起。 ViewPager 和指示此 ViewPager 状态的 View ,有点像选项卡,但它可以显示不同(与通常的选项卡相同,一个 TextView ,但只是文本会改变),它只是实现了一些接口(interface)。程序化地我可以做到这一点,比如

myViewPager.setIndicator(myIndicatorView);

但是,为此我必须在某些父 View 中找到这 2 个 View 并调用此方法。我想简化它,并能够在 xml 模式中简单地管理它。这里是 xml 的例子。

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/someTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<com.example.views.TextTabs
android:id="@+id/info_tabs"
android:layout_width="match_parent"
android:layout_height="@dimen/info_tabs_height"
android:background="@drawable/header_gradient" />

<com.example.views.InfoPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
custom:tabs="@id/info_tabs" />
</LinearLayout>

我创建了自定义属性并将其放入对 View ID 的引用中。所以我的构造函数是:

public ViewPager(Context context, AttributeSet attrs) {
super(context, attrs);

//Getting view id from xml attribute
TypedArray attr = context.obtainStyledAttributes(attrs, R.styleable.ViewPager);

//This id equals R.id.info_tabs
int id = attr.getResourceId(R.styleable.ViewPager_tabs, -1);
if (id != -1) {
//i want to find view from all activity
View tabs = ((Activity) context).findViewById(id);
if (tabs != null && tabs instanceof ViewPagerTabs) {
// if tabs finded
mTabs = (ViewPagerTabs) tabs;
setIndicator(mTabs);
}
}
}

问题是我无法通过 ID 查看。这个想法是指示器 View 可以在不同的地方,它可以与分页器同级,它可以在分页器的更高级别等等。这就是为什么我试图从 Activity 中找到它。但我什至无法从父 View 中找到它,因为 getParent 返回 null。

那么我怎样才能从另一个不是他 parent 的 View 中找到 View 呢?或者您有其他解决方案吗?

最佳答案

问题是 View 没有附加,所以我将 onAttachChangeListener 添加到这个 View ,当它被附加时我再次搜索 View 。

//This id equals R.id.info_tabs
int id = attr.getResourceId(R.styleable.ViewPager_tabs, -1);
if (id != -1) {
//i want to find view from all activity
View tabs = ((Activity) context).findViewById(id);
if (tabs != null && tabs instanceof ViewPagerTabs) {
// if tabs finded
mTabs = (ViewPagerTabs) tabs;
setIndicator(mTabs);
} else {

//If we didn't find view - add listener, and waiting while this view will attached
addOnAttachStateChangeListener(new OnAttachStateChangeListener {
@Override
public void onViewAttachedToWindow(View v) {
View tabs = ((Activity)getContext()).findViewById(mTabsViewId);
//
if (tabs != null && tabs instanceof ViewPagerTabs) {
setIndicator((ViewPagerTabs) tabs);
}
//Remove this listener it's not usefull anymore
removeOnAttachStateChangeListener(this);
}

@Override
public void onViewDetachedFromWindow(View v) {
}
});
}
}

关于android - 从另一个 View 而不是父 View 获取 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19024606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com