Java 从线性布局中获取子对象
我创建了布局文件,由一个linearlayout和主布局中的两个嵌套linearlayout组成。当我使用getParent方法时,它会选择第二个嵌套的linearlayout。我的目标是第一个嵌套线性布局。所以我给了第一个嵌套的linearlayout一个称为linear_top的ID。然后我在onCreateView、test和debug中声明,我没有运气它显示为null 我的目标是animatedgimageviewJava 从线性布局中获取子对象,java,android,android-layout,get-childitem,Java,Android,Android Layout,Get Childitem,我创建了布局文件,由一个linearlayout和主布局中的两个嵌套linearlayout组成。当我使用getParent方法时,它会选择第二个嵌套的linearlayout。我的目标是第一个嵌套线性布局。所以我给了第一个嵌套的linearlayout一个称为linear_top的ID。然后我在onCreateView、test和debug中声明,我没有运气它显示为null 我的目标是animatedgimageview <LinearLayout xmlns:android="http
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linear_top"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/music_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Love Story"
android:textAppearance="?android:attr/textAppearanceLarge" />
<com.music.flow.lib.AnimatedGifImageView
android:id="@+id/music_anim"
android:layout_width="match_parent"
android:layout_height="76dp"
android:scaleType="fitXY"
android:contentDescription="Animation"
/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RatingBar
android:id="@+id/music_rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="40dp"
android:numStars="4"
android:rating="3.5" />
<ImageView
android:id="@+id/btn_playmusic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:src="@drawable/resume" />
</LinearLayout>
linearTop = (LinearLayout) v.findViewById(R.id.linear_top);
AnimatedGifImageView animatedGifImageView =
(AnimatedGifImageView) linearTop.getChildAt(1); /* Null Exception */
子视图从0索引。换句话说,第一个子视图是0,第二个子视图是1。。。等等 还有,为什么不直接通过它的ID获取ImageView
AnimatedGifImageView musicAnim = (AnimatedGifImageView) findViewById(R.id.music_anim);
你的代码是这样的吗?您得到的是NullPointerException,因为在onCreateView中,参数View v
可能为null,如文档中所述。你在用碎片吗?如果没有,则不要使用onCreateView
。将代码放在onCreate
中,如下所示:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearTop = (LinearLayout) findViewById(R.id.linear_top);
ImageView animatedGifImageView = (ImageView) linearTop.getChildAt(1);
setContentView(R.layout.activity_nested_linearlayout);
}
此外,正如声音概念所提到的,您可以尝试直接使用视图id获取视图,而不是使用索引手动获取视图。您在哪里声明了OnCreateView方法?通常,findViewById从活动的livecycle方法调用。那么就不必使用父容器来访问此方法。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearTop = (LinearLayout) findViewById(R.id.linear_top);
ImageView animatedGifImageView = (ImageView) linearTop.getChildAt(1);
setContentView(R.layout.activity_nested_linearlayout);
}