簡體   English   中英

在活動之間傳輸textview數據?

[英]Transfer textview data between activities?

我目前正在制作一個具有edittext和2個按鈕的應用程序,每次我向edittext中寫入內容,然后按button1時,都會添加一個新的textview。 這是代碼:

public void novVnos (View v){
    EditText eText = (EditText) findViewById(R.id.editText1);
    LinearLayout mLayout = (LinearLayout) findViewById(R.id.linearLayout);

    mLayout.addView(createNewTextView(eText.getText().toString()));
}

private TextView createNewTextView (String text){
    final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    final TextView newTextView = new TextView(this);

    newTextView.setLayoutParams(lparams);
    newTextView.setText(text);
    return newTextView;
}

基本上,我正在做的是添加新的“玩家”,添加完所有這些后,我想按一下button2。 Button2打開一個新活動,新活動應讀取我在上一個活動中添加的所有textview。

我要做的是創建一個“ Player” class並在Player.java類中創建一個static ArrayList<String> players 每次調用createNewTextView(textView)請將任何可變text添加到players ArrayList

在您的下一個Activity您只需調用Player.players.get(index)或您需要在下一個類中執行所需的任何ArrayList函數。 您也可以在當前的Activity創建此ArrayList ,並將其作為Intent中的Intent傳遞,但我認為為玩家創建一個單獨的類是最簡單的。

您的ArrayList顯然不需要保留String 它可以容納任何想要的內容,包括Player對象。

ArrayList文檔

這是一個例子:

在第一個活動中:

   Button search = (Button) findViewById(R.id.Button02);
    search.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {


            Intent intent = new Intent(MainActivity.this, result.class);
            Bundle b = new Bundle();

            EditText searchtext = (EditText) findViewById(R.id.searchtext);

            b.putString("searchtext", searchtext.getText().toString());
                   //Add the set of extended data to the intent and start it
            intent.putExtras(b);
            startActivityForResult(intent,RESULT_ACTIVITY);
        }
    });

在onCreat的第二個活動中:

 Bundle b = getIntent().getExtras();
    String searchtext = b.getString("searchtext"); //here you get data then use it as you want

  //here I use it to show data in another edittext
     EditText etSearch = (EditText) findViewById(R.id.searchtext2);
     etSearch.setText(searchtext);

實現“玩家”類將是一種方法。 在這方面,您不必擔心在兩個活動之間傳輸數據。 您可以使用Singleton方法來確保您的類僅定義一次。 您需要確保僅定義一次,因為如果用戶關閉應用程序或殺死應用程序,那么當他再次打開應用程序時,它將創建另一個類,因此所有數據都將丟失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM