2011-05-07 4 views
0

안드로이드 앱에서 "임의"버튼을 클릭하면 앱이 first.xml, second.xml 또는 third.xml에서 임의의 xml 파일을 보여줍니다. 이 모든 괜찮 작동하지만 100 + xml 파일이 있으면 그것을 구현하는 더 쉽거나 좋은 방법이 있는지 궁금해.안드로이드에서 랜덤 XML 파일보기

private Integer [] mImageIds = { 
     R.drawable.one, 
     R.drawable.two, 
     R.drawable.three, 
     }; 
    private static final Random rgenerator = new Random(); 

    private ImageView iv; 

    . 
    . 
    . 

    Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)]; 

    iv = (ImageView) findViewById(R.id.imageviewyeah); 
    iv.setImageResource(q); 

이 내 main.xml에 보이는 방법은 다음과 같습니다 :

<?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     > 
<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello" 
    /> 
<Button 
     android:id="@+id/first_button" 
     android:onClick="change" 
     android:text="first" 
     android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
     /> 
<Button 
     android:id="@+id/second_button" 
     android:onClick="change" 
     android:text="second" 
     android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
     /> 
<Button 
     android:id="@+id/third_button" 
     android:onClick="change" 
     android:text="third" 
     android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
     /> 
<Button 
     android:id="@+id/random_button" 
     android:onClick="change" 
     android:text="random" 
     android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
     /> 

이 코드입니다

나는 임의 ImageViews을 보여줍니다 (잘 작동) 일부 코드를 발견 버튼을 클릭하면 처리됩니다.

package com.random; 

    import java.util.Random; 

    import android.app.Activity; 
    import android.content.Intent; 
    import android.os.Bundle; 
    import android.view.View; 

    public class Main extends Activity { 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
} 

public void change(final View view){ 
    switch (view.getId()) { 
    case R.id.first_button: 
     startActivity(new Intent(this, FirstPage.class)); 
     break; 
    case R.id.second_button: 
     startActivity(new Intent(this, SecondPage.class)); 
     break; 
    case R.id.third_button: 
     startActivity(new Intent(this, ThirdPage.class)); 
     break; 
    case R.id.random_button: 

     Random random = new java.util.Random(); 
     int rand = random.nextInt(3); 

     switch (rand) { 
     case 0: 
      startActivity(new Intent(this, FirstPage.class)); 
      break; 
     case 1: 
      startActivity(new Intent(this, SecondPage.class)); 
      break; 
     case 2: 
      startActivity(new Intent(this, ThirdPage.class)); 
      break; 
      } 
     } 
    } 
} 

도움을 주시면 감사하겠습니다.


이제는 비슷한 질문을합니다. 지금까지 "임의"버튼을 구현했습니다. 클릭하면 임의의 XML 파일이 표시됩니다. 참고 : 콘텐츠 (TextViews, ImageViews)는 XML 파일에서 다르지만 Java 코드 (버튼 등을 클릭)는 동일합니다! 당신이 "임의"- 버튼을 클릭하면 코드의

:

switch (view.getId()) { 
    case R.id.first_button: 
     startActivity(new Intent(this, FirstPage.class)); 
     break; 
    case R.id.second_button: 
     startActivity(new Intent(this, SecondPage.class)); 
     break; 
    case R.id.third_button: 
     startActivity(new Intent(this, ThirdPage.class)); 
     break; 
    case R.id.random_button: 
     Intent intent = new Intent(this, DisplayRandomPage.class); 
     startActivity(intent); 

을이이 DisplayRandomPage.class에

public class DisplayRandomPage extends Activity { 

private Integer [] mLinearLayoutIds = { 
     R.layout.one 
     R.layout.two, 
     R.layout.three 
     }; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 


    Random random = new java.util.Random(); 
    int rand = random.nextInt(3); 

    setContentView(mLinearLayoutIds[rand]); 
      } 
    } 

나는를 작성하면된다 싶습니다 무엇 DisplaySpecificPage.class. 위에서 switch-case-clause을 사용하여 main.class를 보여 줬습니다. 따라서 첫 번째 버튼을 클릭하면 FirstPage.class가 시작되고 두 번째 클릭하면 SecondPage.class가 시작됩니다. 그래서 각 XML 파일에 대해 나는 새로운 자바 클래스를 생성해야하지만, 다른 자바 클래스는 모두 동일하다. XML 파일 만 다릅니다. 그래서 나는이 같은 것을 넣어 싶습니다

의사 코드 :

case R.id.first_button: 
    startActivity(new Intent(this, DisplaySpecificPage.class)) with R.layout.first_page; 
    break; 

은 내가 어떻게가 레이아웃 (R.layout.first_page)에서 ID를 전달합니까?

답변

1

라는 다른 레이아웃을 제외하고는 수업이 모두 같은 일을 할 경우, 단일 디스플레이 클래스

public class DisplayPage extends Activity 

을 생성하고 의도 엑스트라에 그것을 레이아웃의 ID를 보낼 수 있습니다.

당신이 (당신의 레이아웃을 가정
Class c = Class.forName("com.random.R$layout"); 
Integer iLayout = new Integer(c.getField("layout"+rand).getInt(new R.layout())); 

뭔가를 수행하여 ID를 얻을 수 있습니다

이 layout1.xml라고, layout2.xml 등)

, 당신의 DisplayPage에

Intent intent = new Intent(this, DisplayPage.class); 
intent.putExtra("Layout", iLayout); 
startActivity(intent); 

그것을 보내기

당신은 또한 INT를 포함 onSaveInstanceState를 오버라이드 (override) 할 수 있습니다
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 

    // default value 
    int iLayout = R.id.main; 

    if (savedInstanceState != null) 
    { 
    iLayout = savedInstanceState.getInt("Layout"); 
    } 
    else 
    { 
    Bundle extras = getIntent().getExtras(); 
    if (extras != null) 
    { 
     iLayout = extras.getInt("Layout"); 
    } 
    } 

    setContentView(iLayout); 

} 

같은 작업을 수행하여 그것을 다시 얻을 예를 들어, 그래서, 화면 방향을 변경한다고해서 그것이 무엇을 보여줬는지 잊어 버리는 것은 아닙니다.


try 
{ 
    Class c = Class.forName("com.random.R$layout"); 
    Field[] aFields = c.getFields(); 

    Random random = new Random();  
    boolean isUsableLayout = false; 
    Integer iLayout = 0; 

    while (!isUsableLayout) 
    { 
    int rand = random.nextInt(aFields.length);  
    iLayout = new Integer(c.getField(aFields[rand].getName()).getInt(new R.layout())); 

    if (iLayout != R.layout.main) 
    { 
     isUsableLayout = true; 
    } 
    } 

    Intent intent = new Intent(this, DisplayPage.class); 
    intent.putExtra("Layout", iLayout); 
    startActivity(intent); 
} 
catch (Exception e) 
{ 
    e.printStackTrace(); 
} 
+0

안녕 벤! 게시 한 내용을 수행했으며 올바르게 작동합니다! 그러나 나는 layout1, layout2, ...로 3 개의 샘플 레이아웃의 이름을 변경했다. 사실 내 레이아웃에는 비슷한 이름이 없다. 나는 이런 식으로 생각했다 :private 정수 [] mLinearLayoutIds = { R.id.one, R.id.two, R.id.three, }}; 이것이 작동하는 방법에 대한 단서가 있습니까? – BenjaminButton

+0

'Field [] afFields = c.getFields()'를 사용하여 모든 레이아웃 id를 Fields 배열로 반환하고 그 중 하나를 무작위로 선택하고, 사용하지 않으려는 레이아웃이 아닌지 확인하십시오 (예 : , 메인), 그것을 사용합니다. 그렇지 않으면 배열에 100 개 이상의 모든 레이아웃 ID를 직접 작성해야합니다. –

+0

안녕하세요! 메신저가 여기 붙어있는 것 같습니다. 전에는 실제로 필드를 사용하지 않았습니다. 그래서 이것은 "switch"case 절의 코드 스 니펫입니다 :'Class c = Class.forName ("com.random.R $ layout"); java.lang.reflect.Field [] afFields = c.getFields();'이제는 DisplayPage.class에 전달하는 방법을 모릅니다. 그리고 그 곳에서 사용하는 방법을 모릅니다. 마지막으로 ID는 내가 레이아웃을 확인해야하는지 알기를 원합니다 (예 : 메인). 레이아웃 ID를 부여하지 않거나 완전히 잘못되었습니다. 그렇다면 원하지 않는 레이아웃을 어떻게 확인합니까? '(afFields == main이면) 다시 랜덤 화하면됩니다. – BenjaminButton