我的项目曾经做过这样的事情:
public class MenuScreen extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_screen);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_menu_screen, menu);
return true;
}
public void onScanCodeClick(View view) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
try {
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException aex) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("No Application Found");
builder.setMessage("We could not find an application to scan QR CODES."
+ " Would you like to download one from Android Market?");
builder.setPositiveButton("Yes, Please",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW);
marketIntent.setData(Uri
.parse("market://details?id=com.google.zxing.client.android"));
startActivity(marketIntent);
}
});
builder.setNegativeButton("No, Thanks", null);
builder.create().show();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
Intent intent2 = new Intent();
intent2.setClass(this, MenuCodeSuccess.class);
intent2.putExtra("qrDetails", contents);
startActivity(intent2);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
}
onScanCodeClick
只是按钮的 onClickListener。您当然可以初始化您的按钮并改用此代码。
这是一个xml布局:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="2" >
<Button
android:id="@+id/menuScreen_SCANCODE"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onScanCodeClick"
android:text="@string/scanButton" />
</TableLayout>
请不要在意布局的风格,您所需要的只是在 java 类中。:) 但无论如何它应该可以工作。