2016-07-13 42 views
-1

我是在android studio中學習數組的新手。請詳細介紹一些例子。我在這裏寫了一個例子,我想將MainActivity中的Array數據顯示到second_page活動中。Android Studio如何將Array數據傳遞給另一個活動的TextView?

MainActivity.java

public class MainActivity extends AppCompatActivity { 

String my_array[]={"dog","cat","tiger"}; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
} 

public void next_page(View view){ 
    Intent intent = new Intent(this,second_page.class); 
    intent.putExtra("my_array_next", my_array); 
    startActivity(intent); 
} 

}

second_page.java

public class second_page extends MainActivity { 

TextView get_data; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.second_page); 

    get_data=(TextView)findViewById(R.id.tv); 
    Intent intent=getIntent(); 

    // coding here to display the array data 
    // sth like abc.setText(display_array_data); 

} 

請指點。謝謝!

+0

我想你應該閱讀使用意圖的http://www.vogella.com/tutorials/的基本知識AndroidIntent/article.html –

+0

嘗試我的解決方案http://stackoverflow.com/a/38349785/3981656 –

回答

0

second_page.java,收到您通過Intent傳遞數組並將其設置爲你的TextView這樣

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    ... 
    String[] array = intent.getStringArrayExtra("my_array_next"); 

    // TextView display a String so you should convert your Array to String 
    String str1 = Arrays.toString(array); 
    get_data.setText(str1); 
} 
0

先取數組:

Intent intent = getIntent(); 
List array; 
if (intent.getExtras() != null) { 
    array= intent.getExtras().getBoolean("my_array_next"); 
} 

然後打印

get_data.setText(array.toString()); 
0

發送級別:

Intent intent = new Intent(this, ClassB); 
String[] myStrings = new String[] {"test", "test2"}; 
intent.putExtra("strings", myStrings); 
startActivity(intent); 

Reciving類別:

public void onCreate() { 
    Intent intent = getIntent(); 
    String[] myStrings = intent.getStringArrayExtra("strings"); 
} 
1

如果您試圖從一個Activity向另一個Activity發送字符串數組,則可以在Intent中完成。

在ClassA的:

Intent intent = new Intent(this, ClassB); 
String[] my_array = new String[]{"dog","cat","tiger"}; 
intent.putExtra("myArr", my_array); 
startActivity(intent); 

在ClassB的:

public void onCreate() { 
    Intent intent = getIntent(); 
    String[] myStrings = intent.getStringArrayExtra("myArr"); 
} 

這或許可以幫助你

相關問題