2017-01-25 11 views
0

でショーをdosent tで表示ViewGroupAndroidのスイッチは、私はこのようなウィジェットを作成したいのViewGroup

この場合はちょうどSwitchのテキスト"hello"が表示されています。

public class TestView extends ViewGroup { 
    ... 
    private void init() { 
     imageView = new ImageView(getContext()); 
     imageView.setImageResource(R.drawable.clock_icon); 

     aSwitch = new Switch(getContext()); 
     aSwitch.setText("hello"); 
     aSwitch.setChecked(true); 

     addView(imageView); 
     addView(aSwitch); 

    } 

    @Override 
    protected void onSizeChanged(int w, int h, int oldw, int oldh) { 
     super.onSizeChanged(w, h, oldw, oldh); 
     imageView.layout(0, 50,100, 70); 
     aSwitch.layout(50,50,100,70); 
    } 
... 

答えて

0

TNX @Gugalo: https://developer.android.com/reference/android/view/View.html#requestLayout()

唯一の問題
は、何らかの理由で、それはあなたがこのような何かを行う必要がありますView.onSizeChanged(int w, int h, int oldw, int oldh)から動作しません、ということです。

@Override 
    protected void onSizeChanged(int w, int h, int oldw, int oldh) { 
     super.onSizeChanged(w, h, oldw, oldh); 
     aSwitch.measure(w,h); 
     aSwitch.layout(0, 0, aSwitch.getMeasuredWidth(), aSwitch.getMeasuredHeight()); 
    } 
0

レイアウトのリソースファイルを作成する方が簡単かもしれません:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 
    <ImageView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/clock_icon"/> 
    <Switch 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Hello" 
     android:checked="true"/> 
</LinearLayout> 

必要なときにプログラム的にそれを膨らま:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    return inflater.inflate(R.layout.your_resource_file, container, false); 
} 
+0

@Charlieありがとうございますが、私はプログラミングで作成したいと思います。 – Reza

0

私はViewGroup.layout(int l, int t, int r, int b)が正しいapprouchであることを確信していないですこの方法は図面ビューの全体的な流れの一部にすぎないので、ビューのサイズと位置を定義するには

ViewGroup.layout(int l, int t, int r, int b)は、レイアウトメカニズムの第2段階です。 https://developer.android.com/reference/android/view/ViewGroup.html#layout(intを(最初に測定された)、int型、int型、int型)

しかし、とにかく、あなたはView.requestLayout()を呼び出そうとすることができます。このビューのレイアウトを無効にした何かが変更されたときにこれを呼び出します。私はあなたの説明をすることを解決

@Override 
protected void onSizeChanged(int w, int h, int oldw, int oldh) { 
    super.onSizeChanged(w, h, oldw, oldh); 
    imageView.layout(0, 50,100, 70); 
    aSwitch.layout(50,50,100,70); 
    post(new Runnable() { 
     @Override 
     public void run() { 
      imageView.requestLayout(); 
      aSwitch.requestLayout(); 
     } 
    }); 
} 
関連する問題