从Android中的Activity获取EditText

时间:2012-06-08 17:41:04

标签: android android-widget

我想制作和API在斑马打印机上打印票证,我有我的主要活动(仅用于测试):

public class ZebraPrinterActivity extends Activity {
public EditText macAddress;
public Button testButton;
public Printer zebra;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    macAddress = (EditText) this.findViewById(R.id.editText1);
    testButton = (Button) this.findViewById(R.id.button1);

    zebra = new Printer(new ZebraPrinterActivity());
    testButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            new Thread(new Runnable() {
                public void run() {

                }
            }).start();
        }
    });
}}

我的班级(API)名为Printer:

public class Printer {

private ZebraPrinterConnection zebraPrinterConnection;
private ZebraPrinter zebra;
private String MAC;

public Printer (Activity activity) {
    zebraPrinterConnection = null;
    zebra = null;
    activity....get Edit Text
    this.MAC = MAC;
}}

我需要的是从早期活动中获取编辑文本,有没有办法做到这一点?

1 个答案:

答案 0 :(得分:3)

你试过这个吗?

EditText macAddress = (EditText) activity.findViewById(R.id.editText1);
String macAddressString = macAddress.getText();

由于访问非UI线程中的UI元素的限制,EditText等视图上的某些操作可能无效。如果发生这种情况,请参阅此SO问题,了解从另一个线程访问EditText元素的方法:

Do some Android UI stuff in non-UI thread

或者关于同一主题的Android博文:

Painless Threading | Android Developers Blog