2014-09-01 2 views
0

Я создал файл макета, состоящий из одного linearlayout и двух вложенных linearlayout внутри основного. Когда я использую метод getParent, он выбирает второй вложенный linearlayout. Моя цель была первой вложенной linearlayout. Поэтому я даю первый вложенный linearlayout идентификатор, называемый linear_top. Затем я объявлял в onCreateView, тестировал и отлаживал, мне не повезло, это показывает, что это null.Получение ребенка от линейного макета

Моя цель была AnimatedGifImageView

<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> 

OnCreateView

linearTop = (LinearLayout) v.findViewById(R.id.linear_top);     
AnimatedGifImageView animatedGifImageView = 
        (AnimatedGifImageView) linearTop.getChildAt(1); /* Null Exception */ 
+0

Где вы объявили метод OnCreateView? Обычно findViewById вызывается из метода livecycle для действия. Тогда нет необходимости использовать родительский контейнер для доступа к этому методу. –

ответ

1

просмотров за детьми индексируются с 0. Другими словами, первый взгляд ребенок 0, то второй вид ребенка - 1 ... и так далее.

Кроме того, почему бы вам просто не получить ImageView по его ID?

AnimatedGifImageView musicAnim = (AnimatedGifImageView) findViewById(R.id.music_anim); 
0
@Override 
    public View onCreateView(View v, String name, Context context, 
      AttributeSet attrs) { 
     LinearLayout linearTop = (LinearLayout) v.findViewById(R.id.linear_top); 
     ImageView animatedGifImageView = (ImageView) linearTop.getChildAt(1); // NullPointer 

     return super.onCreateView(v, name, context, attrs); 
    } 

ли ваш код, как это? Вы получаете исключение NullPointerException, потому что в onCreateView параметр View v может быть нулевым, как указано в документах here. Вы используете фрагменты? Если нет, то не используйте 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); 
} 

также, как то, что упоминается Sound зачатие, вы можете просто попытаться получить представление непосредственно, используя его идентификатор вместо того, чтобы вручную получить его с помощью индекса.

 Смежные вопросы

  • Нет связанных вопросов^_^