更新 - 最後に解決策を参照してください。今必要なのは説明だけです。検索しても同じ質問が見つかりませんでした
カスタム Viewpager を作成し、attrs.xml でカスタム属性を定義しました
ビューページャーコンストラクターで属性を取得しようとすると、意味のある値を取得できません。使ってみた
abstract int getAttributeIntValue(String namespace, String attribute, int defaultValue)
「属性」の整数値を返します。
public MyViewPager(Context context, AttributeSet attrs) {
Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeUnsignedIntValue("http://schemas.android.com/apk/res-auto","view_pager_type",9));
Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeIntValue("http://schemas.android.com/apk/res-auto","view_pager_type",9));
Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","view_pager_type"));
Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","garbage"));
ご覧のとおり、attrs.getAttributeValue は文字列を処理しましたが、私には意味がありません。
これはログ ステートメントからの出力です。見つからない場合は 9 がデフォルトです。@213 の数値がわかりません
ViewPagerType:9
ViewPagerType:9
ViewPagerType:@2131230723
ViewPagerType:null
これは私のattrs.xmlです
<resources>
<declare-styleable name="AutoResizeTextView">
<attr name="ttf_name" format="string"/>
</declare-styleable>
<declare-styleable name="ViewPagerType">
<attr name="view_pager_type" format="integer"/>
</declare-styleable>
</resources>
これが私のレイアウトです
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<org.rh.ellierides.MyViewPager xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/textPager"
app:view_pager_type="@integer/text_viewpager"
android:orientation="horizontal"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="24"
tools:context=".Main">
これはinteger.xmlです
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="text_viewpager">1</integer>
<integer name="image_viewpager">2</integer>
</resources>
2 つの個別のビューページャーを作成するだけだと思いますが、それでもこれを理解したいと思います。
更新 解決策を見つけましたが、最初の解決策が機能しなかった理由がわからないので、引き続き回答してください
TypedArray a = null;
try {
a = getContext().obtainStyledAttributes(attrs, R.styleable.ViewPagerType);
int viewpagerType = a.getInt(R.styleable.ViewPagerType_view_pager_type, 9);
Log.d(Constant.TAG, "viewpagerType:" + viewpagerType);
} finally {
if (a != null) {
a.recycle(); // ensure this is always called
}
}