简体   繁体   English

单击项目从ListActivity返回上一个活动

[英]Return to previous Activity from ListActivity on item click

I have a SettingsActivity with a "Scan" button at the bottom: 我有一个SettingsActivity,底部有一个“扫描”按钮:

设置

When that button is clicked, it starts a ListActivity: 单击该按钮时,它将启动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? 用什么方法,改为调用的Toast.makeText()在上述onListItemClick()方法?

I agree with other answers that calling finish is the solution. 我同意其他答案,即完成通话是解决方案。 But you should know few things about using finish method. 但是您应该了解有关使用Finish方法的一些知识。

  1. The method that called finish() will run to completion. 调用finish()的方法将运行完成。 The finish() operation will not even begin until you return control to Android. 除非您将控制权返回给Android,否则finish()操作甚至不会开始。

So, you should put a return statement after that finish, because the method that called finish will be executed completely otherwise. 因此,您应该在该完成之后放置一个return语句,因为否则将完全执行调用finish的方法。

  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. 请在使用finish()方法时记住这一点。

I think 我认为

ActivityName.this.finish();

should be enough. 应该足够了。

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

ScanningActivity.this.finish();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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