2015-02-19 4 views
0

У меня есть макет activity_main, что (помимо всего прочего) показывает ImageView:Put генерируется ImageView в XML ImageView

<ImageView 
     android:id="@+id/profileImageView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/textView2" 
     android:layout_alignLeft="@+id/login_button" /> 

Я создал класс, который расширяет ImageView и показывает анимированный GIF:

public class AnimatedGif extends ImageView 
{ 
    private Movie mMovie; 
    private long mMovieStart = 0; 

    public AnimatedGif(Context context, InputStream stream) 
    { 
     super(context); 
     mMovie = Movie.decodeStream(stream); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) 
    { 
     canvas.drawColor(Color.TRANSPARENT); 
     super.onDraw(canvas); 
     final long now = SystemClock.uptimeMillis(); 
     if (mMovieStart == 0) 
     { 
      mMovieStart = now; 
     } 
     final int realTime = (int)((now - mMovieStart) % mMovie.duration()); 
     mMovie.setTime(realTime); 
     mMovie.draw(canvas, 10, 10); 
     this.invalidate(); 
    } 
} 

В основном случае я пользуюсь следующим кодом:

setContentView(R.layout.activity_main); 
. 
. 
. 
InputStream stream = this.getResources().openRawResource(R.drawable.searching_gif); 
AnimatedGif gifImageView = new AnimatedGif(this, stream); 
ImageView im = (ImageView)findViewById(R.id.profileImageView); 

Как я могу это сделать im покажет gifImageView ??

+0

Используйте этот пользовательский ImageView вместо этого в XML следующим образом: '< com.packagename.AnimatedGif android: id = "@ + id/profileImageView" и в java-классе вместо изображения ImageView; 'use' AnimatedGif image; ' –

+0

Хранить все остальное одинаково. Просто измените '

+0

@Tushar он вылетает на setContentView (R.layout.activity_main); – SharonKo

ответ

0

вы не можете. По крайней мере, как вы об этом думаете. Вам нужны минимальные изменения, чтобы загрузить ваш AnimatedGif непосредственно в макет. Первый конструктор, который принимает в качестве параметра Context и AttributeSet:

public AnimatedGif(Context context, AttributeSet attrs) { 

} 

Таким образом, вы можете добавить его непосредственно в качестве элемента в XML, указав полный квалифицированный пакет класса

<com.package.AnimatedGif 
    android:id="@+id/profileImageView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/textView2" 
    android:layout_alignLeft="@+id/login_button" /> 

теперь вы, вероятно, хотите, чтобы пользовательский атрибут указывал gif, который вы хотите загрузить. Таким образом, вы можете объявить в вашем файле attr.xml

<declare-styleable name="AnimatedGif"> 
    <attr name="gifres" format="integer" /> 
</declare-styleable> 

и внутри конструктора вы можете загрузить его как

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AnimatedGif); 
int value = a.getInt(R.styleable.AnimatedGif_gifres, 0)); 
stream = context.getResources().openRawResource(value); 
a.recycle(); 
0

Как я могу сделать, что им покажут gifImageView ??

Поскольку activity_main.xml является макет для деятельности, в которой нужно добавить пользовательские ImageView с помощью кода:

1. Используйте LinearLayout в activity_main.xml в корневом Layout и установите orientation в vertical

2. Присвоить ид к корневому расположению activity_main.xml:

 android:id="@+id/main_layout" 

3. Получить корневой макет в onCreate метод:

 LinearLayout linearLayout = (LinearLayout)findViewById(R.id.main_layout); 

4. Теперь добавьте gifImageView объект представления LinearLayout:

 linearLayout.addView(gifImageView); 
Смежные вопросы