简体   繁体   中英

Return to previous Activity from ListActivity on item click

I have a SettingsActivity with a "Scan" button at the bottom:

设置

When that button is clicked, it starts a ListActivity:

(I plan to switch to fragments later. For now I'd like to use activities.)

<Button
    android:id="@+id/scanButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="startScanning"
    android:text="Scannen und Beacon ausw\u00E4hlen..." />

public void startScanning(View v) {
    Intent i = new Intent(this, ScanningActivity.class);
    startActivity(i);
}

When an item (a bluetooth device) has been clicked in that list - I save that item and display a toast, telling the user to go to the previous screen:

截图

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    BluetoothDevice device = (BluetoothDevice) getListView().getItemAtPosition(position);
    String address = device.getAddress();
    mEditor.putString(CommonConstants.PREF_ADDRESS, address);
    mEditor.commit();

    Toast.makeText(this,
        "Ger\u00E4t-Adresse gespeichert, bitte Dienst neu starten", 
        Toast.LENGTH_SHORT)
        .show();
}

My (probably very basic) question: instead of displaying the toast, how can my app just return to the previous screen?

What method to call instead of Toast.makeText() in the above onListItemClick() method?

I agree with other answers that calling finish is the solution. But you should know few things about using finish method.

  1. The method that called finish() will run to completion. The finish() operation will not even begin until you return control to Android.

So, you should put a return statement after that finish, because the method that called finish will be executed completely otherwise.

  1. You can use this method in case when you don't want this activity to load again and again when the user presses back button. Because it clears the activity from the backstack also.

Please remember this while using finish() method.

I think

ActivityName.this.finish();

should be enough.

您需要做的就是像这样关闭当前活动

ScanningActivity.this.finish();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM