2012-04-28 5 views
0

저는 Android app을 가지고 있으며 서로 비슷한 두 개의보기를 원합니다. 예 :android app에서보기를 동적으로 선택하십시오.

<Button 
    android:id="@+id/ok" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:text="OK" /> 

<Button 
    android:id="@+id/ok" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="OK" /> 

통지 유일한 변경 제가 centerHorizontal 라인을 제거하는 것이된다. 그러나 이것은 단순한 예입니다.

지금, 내가보기 A를 사용 때때로 (전직 임의의 FUNC를 사용하는) 것을, 응용 프로그램을 만들려면 때로는보기 B.

이 런타임에 "뷰 전환"할 것이 가능합니다? 두 개의보기를 사용하여이 응용 프로그램을 빌드 할 수 있습니까 (단추가 동일한 ID를 가져야하고 논리를 두 번 구현하지 않음).

감사합니다. 나는 그렇게 생각

+0

중력 사이를 전환 할 수 있는지 확인하십시오. –

답변

0

유일한 방법은 다음과 같습니다

  • 가 자신의 레이아웃 파일의 각 버튼을 가졌어요.
  • 함수 결과에 따라 해당하는 것을 팽창시킵니다.
  • 보기에 추가하십시오.

샘플 코드 :

button_a.xml :

<?xml version="1.0" encoding="utf-8"?> 
<Button xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/ok" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:text="OK" /> 

button_b.xml :

<?xml version="1.0" encoding="utf-8"?> 
<Button xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/ok" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="OK_2" /> 

귀하의 활동

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    LayoutInflater inflater = LayoutInflater.from(this); 

    Button button; 

    if (Math.random() > 0.5) { 
     button = (Button) inflater.inflate(R.layout.button_a, null); 
    } else { 
     button = (Button) inflater.inflate(R.layout.button_b, null); 
    } 

    /* ... 
     Set listeners to the button and other stuff 
     ... 
    */ 

    //find the view to wich you want to append the button 
    LinearLayout view = (LinearLayout) this.findViewById(R.id.linearLayout1); 

    //append the button 
    view.addView(button); 
} 

onCreate에는 없지만 일부 사용자 입력 이후) 레이아웃에서 단추를 제거하고 임의로 선택한 새 단추를 부 풀릴 수 있습니다.

희망이 도움이됩니다.

관련 문제