簡體   English   中英

使userInput從主要活動顯示在Android的第二個活動中

[英]Making userInput from main activity to display on second activity in Android

我在這里看到了一些相關的主題,但是經過多次嘗試,我似乎無法找到解決方案,因此希望有人可以提供幫助。 到目前為止,這是我的代碼(試圖使userInput作為結果出現在第二個活動中)

MainActivity.java

package winfield.joe.wind.v1;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends Activity {

    // public var
    private EditText text;

    // default func
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Toast.makeText(this, "onCreate!", Toast.LENGTH_LONG).show();
        setContentView(R.layout.activity_main);
        // findViewById = Finds a view that was identified by the id attribute
        // from the XML that was processed in onCreate(Bundle).
        // (EditText) = typecast
        text = (EditText) findViewById(R.id.userInput);
    }

    //Will be executed by clicking on the calculate button because we assigned "calc" to the "onClick" Property

    public void calc(View view) {

        RadioButton toKilometers = (RadioButton) findViewById(R.id.toKilometers);
        RadioButton toKnots = (RadioButton) findViewById(R.id.toKnots);

        if (text.getText().length() == 0) {
            // if the text field is empty show the message "enter a valid number" via toast message
            Toast.makeText(this, "enter a valid number", Toast.LENGTH_LONG).show();
        } else {

            int userInput = R.string.userInput;
            Intent i = new Intent(MainActivity.this, SecondActivity.class);
            i.putExtra("userInput", userInput); 
            startActivityForResult(i, 0);
            startActivity(i);

            // parse input Value from Text Field
            double inputValue = Double.parseDouble(text.getText().toString());
            // convert to...
            if (toKilometers.isChecked()) {
                text.setText(String.valueOf(convertToKM(inputValue)));
                // uncheck "to km" Button
                toKilometers.setChecked(false);
                // check "to knots" Button
                toKnots.setChecked(true);
            } else { /* if toKnots button isChecked() */
                text.setText(String.valueOf(convertToKnots(inputValue)));
                // uncheck "to knots" Button
                toKnots.setChecked(false);
                // check "to km" Button
                toKilometers.setChecked(true);
            }
        }

    }


    /*private void putExtra(String string, int result) {
        // TODO Auto-generated method stub
    }*/

    private double convertToKM(double inputValue) {
        // convert knots to km
        return (inputValue * 1.8);
    }

    private double convertToKnots(double inputValue) {
        // convert km to knots
        return (inputValue * 0.539956803);
    }

}

SecondActivity.java

package winfield.joe.wind.v1;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Toast.makeText(this, "onCreate!", Toast.LENGTH_LONG).show();
        setContentView(R.layout.activity_main);
        Intent i = getIntent();
        String userInput = i.getStringExtra("userInput");
    }

    //onClick GoBack method assigned to the Go Back? button which returns the user to main activity from the second activity
    public void GoBack(View view) {

        //AlertDialog appears upon the onclick of the go back button
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Are you sure?");

            // set dialog message
            builder .setCancelable(false)

                    .setPositiveButton("Convert Again",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            //You return to Main Activity  
                            Intent intent = new Intent(SecondActivity.this, MainActivity.class);
                            startActivity(intent);
                        }
                    })

                    .setNeutralButton("Back to Home",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            //You return to the home page
                            Intent intent = new Intent(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_HOME);
                            startActivity(intent);
                        }
                    })

                    .setNegativeButton("View Results",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

        AlertDialog alert = builder.create();
        alert.show();

    }

}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:background="@color/bgColor"
    android:orientation="vertical">

    <!--TITLE-->

    <TextView
        android:id="@+id/titleMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="22dp"
        android:gravity="center"
        android:text="@string/titleMain"
        android:textColor="@color/textColor"
        android:textColorHint="@color/textColor"
        android:textColorLink="#ffffff"
        android:textSize="30sp" />

    <!--USER-INPUT-->

    <EditText
        android:id="@+id/userInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:ems="10"
        android:hint="@+string/userInput"
        android:inputType="numberDecimal"
        android:paddingEnd="40dp"
        android:paddingStart="20dp"
        android:paddingTop="30dp" >

        <requestFocus />
    </EditText>

      <!--TWO RADIO BUTTONS-->
      <LinearLayout

          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:paddingLeft="10dp"
          android:paddingRight="10dp">

          <!--toKNOTS-->

          <RadioButton
              android:id="@+id/toKnots"
              android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:layout_gravity="center"
              android:layout_marginStart="10dp"
              android:layout_marginTop="10dp"
              android:layout_weight="0.04"
              android:checked="true"
              android:text="@string/toKnots" />

          <!--toKM-->

          <RadioButton
              android:id="@+id/toKilometers"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_gravity="center"
              android:layout_marginEnd="20dp"
              android:layout_marginTop="10dp"
              android:text="@string/toKilometers" />

      </LinearLayout>

      <!--CALCULATE-->

      <Button
          android:id="@+id/calc"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:layout_marginEnd="10dp"
          android:layout_marginStart="10dp"
          android:layout_marginTop="30dp"
          android:onClick="calc"
          android:text="@string/calc" />

</LinearLayout>

activity_second.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:background="@color/bgColor"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <!-- TITLE -->

    <TextView
        android:id="@+id/titleResults"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="24dp"
        android:gravity="center"
        android:text="@string/titleResults"
        android:textColor="@color/textColor"
        android:textColorHint="@color/textColor"
        android:textColorLink="#ffffff"
        android:textSize="25sp" />

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="20dp"
        android:layout_marginTop="30dp"
        android:ems="10"
        android:hint="@string/result"
        android:textColorHint="@color/textColor" >
        <requestFocus />
    </TextView>

    <Button
        android:id="@+id/GoBack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="40dp"
        android:text="@string/GoBack"
        android:onClick="GoBack" />

</LinearLayout>

改變這個...

int userInput = R.string.userInput;

...至...

String userInput = text.getText().toString();

R.java文件中的所有內容都是一個static final int ,用於引用資源-它實際上不是資源本身(例如,對於EditText ,不是資源的內容)。

我在您的代碼中看到兩個問題。

首先,將userInput設置為R.string.userInput,這是一種奇怪的imo。 您應該將userInput設置為TextField中的文本:

String userInput = text.getText().toString();

我注意到的第二個問題是您兩次啟動了第二個意圖。 一次是為了結果,一次是沒有結果:

startActivityForResult(i, 0);
startActivity();

如果您不想使用上一個活動的結果,請嘗試刪除startActivityForResult。 您可能誤會了startActivityForResult(i,0)所做的事情。

如果您想從活動中獲取結果,則基本上可以調用startActivityForResult()。 例如,您在MainActivity中,想要在其中顯示照片。 現在,您可以使用startActivityForResult()啟動相機意圖,並在拍照后可以在MainActivity中進行處理。

如果僅要將值傳遞給下一個活動,則只需一個簡單的startActivity()就足夠了。 如果您想了解更多有關此主題的信息,請點擊以下鏈接到文檔:

startActivityForResult()-文檔

**This is the correct way to change information between 2 activity, of corse be careful to activity lifecycle. This code best practice!**

第一次活動

public class MainActivity extends Activity {



private static final String Tag = "ACTIVITY";

    private static final String CONTATORE = "contatore";



TextView  et;
    Button btn,btnLancia;
     int counter = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    et = (TextView) findViewById(R.id.et);
    btn = (Button) findViewById(R.id.btn);
    btnLancia = (Button) findViewById(R.id.btnLancia);

    if(savedInstanceState != null){
        counter = savedInstanceState.getInt(CONTATORE);
    }

    btnLancia.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            lanciaActivity();

        }
    });

    et.setText("" + counter);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ++counter;
            et.setText("" + counter);
        }
    });
    Log.d(Tag, "OnCreate");

}

protected void lanciaActivity() {

    Intent intent = new Intent(this,Activity2.class);
    Bundle bundle = new Bundle();
    bundle.putInt(Activity2.VALUE, counter);
    intent.putExtras(bundle);
    startActivity(intent);
}

@Override
protected void onDestroy() {

    super.onDestroy();
    Log.d(Tag, "OnDestroy");
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    Log.d(Tag, "OnPause");
}

@Override
protected void onRestart() {
    // TODO Auto-generated method stub
    super.onRestart();
    Log.d(Tag, "OnRestart");
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onRestoreInstanceState(savedInstanceState);
    Log.d(Tag, "onRestoreInstanceState");
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    Log.d(Tag, "OnResume");
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
    super.onSaveInstanceState(outState);
    Log.d(Tag, "OnSaveIstantState");

    outState.putInt(CONTATORE, counter);
}

@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    Log.d(Tag, "OnStart");
}

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    Log.d(Tag, "OnStop");
}

}

第二活動

public class Activity2 extends Activity {

private static final String Tag = "ACTIVITY2";
public static final String VALUE = "value";
private static final String VALOREATT = "val";
TextView contatore;
Button button;
int contatoreq;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity2);
    Log.d(Tag, "OnCreate");
    contatore = (TextView) findViewById(R.id.textView1);
    button = (Button) findViewById(R.id.btnDoppio);


    if(savedInstanceState!=null){
        contatoreq = savedInstanceState.getInt(VALOREATT);
    }
    else {
        Intent intetn = getIntent();
        Bundle bundle = intetn.getExtras();
        if(bundle!=null)
            contatoreq = bundle.getInt(VALUE);
    }
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            contatoreq = contatoreq*2;
            contatore.setText("" + contatoreq);
        }
    });


    contatore.setText("" + contatoreq);
}

@Override
protected void onDestroy() {

    super.onDestroy();
    Log.d(Tag, "OnDestroy");
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    Log.d(Tag, "OnPause");
}

@Override
protected void onRestart() {
    // TODO Auto-generated method stub
    super.onRestart();
    Log.d(Tag, "OnRestart");
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onRestoreInstanceState(savedInstanceState);
    Log.d(Tag, "onRestoreInstanceState");
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    Log.d(Tag, "OnResume");
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
    super.onSaveInstanceState(outState);
    Log.d(Tag, "OnSaveIstantState");

    outState.putInt(VALOREATT, contatoreq);
}

@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    Log.d(Tag, "OnStart");
}

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    Log.d(Tag, "OnStop");
}

}

暫無
暫無

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

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