独自のカスタムを作成しようとしていますView
が、に問題がありLayoutParams
ます。
アイデアは拡張することですViewGroup
(LinearLayout
)
public class MyView extends LinearLayout{
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context) {
super(context);
}
public void putContent(){
setOrientation(HORIZONTAL);
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < 5; i++){
View view = inflater.inflate(R.layout.item, null);
TextView tv = (TextView)view.findViewById(R.id.item_text);
tv.setText("Item " + i);
addView(view);
}
}
}
ご覧のとおりputContent
、メソッドはアイテムを膨らませて、私のビューに追加します。こちらがアイテムのレイアウトです
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<TextView android:text="TextView"
android:id="@+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"/>
</LinearLayout>
そしてメイン画面のレイアウト
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android_layout_weight="1"
android:text="@string/hello"
/>
<my.test.MyView
android:id="@+id/my_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android_layout_weight="1"
/>
</LinearLayout>
そしてアクティビティコード
public class Start extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyView myView = (MyView)findViewById(R.id.my_view);
myView.putContent();
}
}
これが私が得たもののスクリーンショットです
したがって、問題は次のとおりです。アイテムのルート要素の属性が無視されます
android:layout_width="match_parent"
android:layout_height="match_parent"
しかし、結果として私はこのようなものを取得したいと思います(addView(view);
この行に置き換えるとこの結果が得られます)
addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F));
したがって、質問は、ハードコーディングされたLayoutParamsなしでこの結果をどのように達成できるかということです。助けてくれてありがとう!
アップデート
またview
、デバッグモードの変数フィールドも確認します。これmLayoutParams
はであり、を使用して親null
にインフレートを追加するとnullではなくなりました。
view
addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F));
しかしmLayoutParams
、ロードされたばかりのビューの子はnullではありません。ビューを膨らませたときに、xmlレイアウトのルート要素のみのLayoutParamsが無視されるのはなぜですか?