2017-01-25 9 views
0

에서 쇼를 dosent t에서 표시 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)은 레이아웃 메커니즘의 두 번째 단계입니다.) 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(); 
     } 
    }); 
}