我对这个问题感到不满。我是Android开发方面的新手。
我想使用ZXING的扫描结果。我将ZXING集成到我的Android应用程序中,扫描工作正常。现在我想使用扫描结果更新主要活动中的TextView。
我该怎么做?
我的代码目前正在执行以下操作:
之后(2)我想使用扫描结果来更新主要活动中的TextView(在我的代码中为tv)。
请帮帮我们 感谢。
我的代码:
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button pressToScan = (Button) findViewById(R.id.button1);
pressToScan.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent data = new Intent("com.google.zxing.client.android.SCAN");
data.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(data, 0);
TextView tv = (TextView) findViewById(R.id.scanResult);
tv.setText(data.getStringExtra("SCAN_RESULT"));
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String contents = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
contents = data.getStringExtra("SCAN_RESULT");
String format = data.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
}
答案 0 :(得分:6)
移动以下块
TextView tv = (TextView) findViewById(R.id.scanResult);
tv.setText(data.getStringExtra("SCAN_RESULT"));
到
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String contents = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
contents = data.getStringExtra("SCAN_RESULT");
String format = data.getStringExtra("SCAN_RESULT_FORMAT");
//moved here
TextView tv = (TextView) findViewById(R.id.scanResult);
tv.setText(contents);
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
[编辑]
在您的活动中添加此内容
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
在清单中更改主要活动以添加android:configChanges =“orientation”
<activity android:name="..."
android:label="@string/appName"
android:configChanges="orientation"
答案 1 :(得分:1)
当被调用的活动设置它的数据时调用startActivityForResult()
,它会在您的活动中调用onActivityResult()
,startActivityForResult()
不会暂停执行方法,所以正确的方法来写这个
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String contents = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
contents = data.getStringExtra("SCAN_RESULT");
String format = data.getStringExtra("SCAN_RESULT_FORMAT");
tv.setText(contents);
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
}