Android Studioにて開発を行っています.Androidで,FrameLayoutを用いて重ねたImageViewとTextViewに対して,動的にリソースを指定したいです.しかし,今書いているコードでは,include文が必要になり,独自リソース定義を使うことができません.どういったコードを書けば,
- 縦横比を問わず,Layout内いっぱいに画像を引き延ばす
- 画像の中央に文字を重ねる
- xmlから,リソース指定して画像やテキストを変更可能
という要件を満たせるのでしょうか.
最後に載せるソースコードが現状のコードになりますが,これらのコードでは,includeにてxmlに組み込むことになり,独自定義のリソースを認識していないようです.(nullになる.)
よろしくお願いします.
xml
1<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:app="http://schemas.android.com/apk/res-auto" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical"> 6 7 <include layout="@layout/my_image_text_view" 8 android:id="@+id/cafeImageView" 9 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" 11 app:mySrc="@drawable/example" 12 app:myText="Example"/> 13</LinearLayout>
java/com.example.mine/view/MyImageTextView.java
Java
1package com.example.mine.view; 2 3/* import 文は省略*/ 4 5public class MyImageTextView extends FrameLayout { 6 7 private AttributeSet attrs; 8 9 public MyImageTextView(Context context, AttributeSet attrs) { 10 super(context, attrs); 11 this.attrs = attrs; 12 } 13 14 @Override 15 protected void onFinishInflate() { 16 super.onFinishInflate(); 17 init(); 18 } 19 20 private void init() { 21 final TextView textView = (TextView) findViewById(R.id.myTextView); 22 final ImageView imageView = (ImageView) findViewById(R.id.myImageView); 23 24 final TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MyImageTextView); 25 26 final Drawable resourceId = typedArray.getDrawable(R.styleable.MyImageTextView_mySrc); 27 if(resourceId!=null) 28 imageView.setImageDrawable(resourceId); 29 30 final String text = typedArray.getString(R.styleable.MyImageTextView_myText); 31 textView.setText(text); 32 33 typedArray.recycle(); 34 } 35 36}
res/layout/my_image_text_view.xml
xml
1<com.example.mine.view.MyImageTextView xmlns:android="http://schemas.android.com/apk/res/android" 2 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 android:layout_width="wrap_content" 5 android:layout_height="wrap_content"> 6 7 <!--xmlns:app="http://schemas.android.com/apk/res-auto"--> 8 <ImageView 9 android:id="@+id/myImageView" 10 android:layout_width="match_parent" 11 android:layout_height="match_parent" 12 android:layout_gravity="center" 13 android:scaleType="fitXY" /> 14 15 <TextView 16 android:id="@+id/myTextView" 17 android:layout_width="wrap_content" 18 android:layout_height="wrap_content" 19 android:layout_gravity="center" 20 android:textAppearance="?android:attr/textAppearanceLarge" /> 21 22</com.example.mine.view.MyImageTextView>
res/values/attrs.xml
xml
1<?xml version="1.0" encoding="utf-8"?> 2<resources> 3 <declare-styleable name="MyImageTextView"> 4 <attr name="mySrc" format="reference" /> 5 <attr name="myText" format="string" /> 6 </declare-styleable> 7</resources>
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。