我使用按钮中的意图打开活动,但应用程序强制关闭。关于解决方案菜单项onClick的错误说明。我甚至都不知道为什么会这样。我只是Android的新手。非常感谢帮助。
这是我的按钮onclick
的代码public class Terminal extends Fragment {
public Terminal(){}
@SuppressLint("InflateParams")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_terminal, container, false);
final Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Quiz
Intent i = new Intent (getActivity(), Term.class);
startActivity(i);
}
});
return rootView;
}
}
这是Term类。它太长了。
private int mPendingPathBroadcasts = 0;
private BroadcastReceiver mPathReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String path = makePathFromBundle(getResultExtras(false));
if (intent.getAction().equals(ACTION_PATH_PREPEND_BROADCAST)) {
mSettings.setPrependPath(path);
} else {
mSettings.setAppendPath(path);
}
mPendingPathBroadcasts--;
if (mPendingPathBroadcasts <= 0 && mTermService != null) {
populateViewFlipper();
populateWindowList();
}
}
};
private static final int FLAG_INCLUDE_STOPPED_PACKAGES = 0x20;
private TermService mTermService;
private ServiceConnection mTSConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
Log.i(TermDebug.LOG_TAG, "Bound to TermService");
TermService.TSBinder binder = (TermService.TSBinder) service;
mTermService = binder.getService();
if (mPendingPathBroadcasts <= 0) {
populateViewFlipper();
populateWindowList();
}
}
public void onServiceDisconnected(ComponentName arg0) {
mTermService = null;
}
};
private ActionBarCompat mActionBar;
private int mActionBarMode = TermSettings.ACTION_BAR_MODE_NONE;
private WindowListAdapter mWinListAdapter;
private class WindowListActionBarAdapter extends WindowListAdapter implements UpdateCallback {
private static final int TextAppearance_Holo_Widget_ActionBar_Title = 0x01030112;
public WindowListActionBarAdapter(SessionList sessions) {
super(sessions);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(Term.this);
String title = getSessionTitle(position, getString(R.string.window_title, position + 1));
label.setText(title);
if (AndroidCompat.SDK >= 13) {
label.setTextAppearance(Term.this, TextAppearance_Holo_Widget_ActionBar_Title);
} else {
label.setTextAppearance(Term.this, android.R.style.TextAppearance_Medium);
}
return label;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
public void onUpdate() {
notifyDataSetChanged();
mActionBar.setSelectedNavigationItem(mViewFlipper.getDisplayedChild());
}
}
private ActionBarCompat.OnNavigationListener mWinListItemSelected = new ActionBarCompat.OnNavigationListener() {
public boolean onNavigationItemSelected(int position, long id) {
int oldPosition = mViewFlipper.getDisplayedChild();
if (position != oldPosition) {
mViewFlipper.setDisplayedChild(position);
if (mActionBarMode == TermSettings.ACTION_BAR_MODE_HIDES) {
mActionBar.hide();
}
}
return true;
}
};
private boolean mHaveFullHwKeyboard = false;
private class EmulatorViewGestureListener extends SimpleOnGestureListener {
private EmulatorView view;
public EmulatorViewGestureListener(EmulatorView view) {
this.view = view;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
if (view.isMouseTrackingActive()) return false;
String link = view.getURLat(e.getX(), e.getY());
if(link != null)
execURL(link);
else
doUIToggle((int) e.getX(), (int) e.getY(), view.getVisibleWidth(), view.getVisibleHeight());
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(velocityY);
if (absVelocityX > Math.max(1000.0f, 2.0 * absVelocityY)) {
if (velocityX > 0) {
mViewFlipper.showPrevious();
} else {
mViewFlipper.showNext();
}
return true;
} else {
return false;
}
}
}
private boolean mUseKeyboardShortcuts;
private View.OnKeyListener mKeyListener = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
return backkeyInterceptor(keyCode, event) || keyboardShortcuts(keyCode, event);
}
/**
* Keyboard shortcuts (tab management, paste)
*/
private boolean keyboardShortcuts(int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
if (!mUseKeyboardShortcuts) {
return false;
}
boolean isCtrlPressed = (event.getMetaState() & KeycodeConstants.META_CTRL_ON) != 0;
boolean isShiftPressed = (event.getMetaState() & KeycodeConstants.META_SHIFT_ON) != 0;
if (keyCode == KeycodeConstants.KEYCODE_TAB && isCtrlPressed) {
if (isShiftPressed) {
mViewFlipper.showPrevious();
} else {
mViewFlipper.showNext();
}
return true;
} else if (keyCode == KeycodeConstants.KEYCODE_N && isCtrlPressed && isShiftPressed) {
doCreateNewWindow();
return true;
} else if (keyCode == KeycodeConstants.KEYCODE_V && isCtrlPressed && isShiftPressed) {
return true;
} else {
return false;
}
}
/**
* Make sure the back button always leaves the application.
*/
private boolean backkeyInterceptor(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && mActionBarMode == TermSettings.ACTION_BAR_MODE_HIDES && mActionBar.isShowing()) {
/* We need to intercept the key event before the view sees it,
otherwise the view will handle it before we get it */
onKeyUp(keyCode, event);
return true;
} else {
return false;
}
}
};
private Handler mHandler = new Handler();
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.e(TermDebug.LOG_TAG, "onCreate");
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mSettings = new TermSettings(getResources(), mPrefs);
Intent broadcast = new Intent(ACTION_PATH_BROADCAST);
if (AndroidCompat.SDK >= 12) {
broadcast.addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);
}
mPendingPathBroadcasts++;
sendOrderedBroadcast(broadcast, PERMISSION_PATH_BROADCAST, mPathReceiver, null, RESULT_OK, null, null);
broadcast = new Intent(broadcast);
broadcast.setAction(ACTION_PATH_PREPEND_BROADCAST);
mPendingPathBroadcasts++;
sendOrderedBroadcast(broadcast, PERMISSION_PATH_PREPEND_BROADCAST, mPathReceiver, null, RESULT_OK, null, null);
TSIntent = new Intent(this, TermService.class);
startService(TSIntent);
if (!bindService(TSIntent, mTSConnection, BIND_AUTO_CREATE)) {
Log.w(TermDebug.LOG_TAG, "bind to service failed!");
}
if (AndroidCompat.SDK >= 11) {
int actionBarMode = mSettings.actionBarMode();
mActionBarMode = actionBarMode;
switch (actionBarMode) {
case TermSettings.ACTION_BAR_MODE_ALWAYS_VISIBLE:
setTheme(R.style.Theme_Holo);
break;
case TermSettings.ACTION_BAR_MODE_HIDES:
setTheme(R.style.Theme_Holo_ActionBarOverlay);
break;
}
}
setContentView(R.layout.term_activity);
mViewFlipper = (TermViewFlipper) findViewById(VIEW_FLIPPER);
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TermDebug.LOG_TAG);
WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
int wifiLockMode = WifiManager.WIFI_MODE_FULL;
if (AndroidCompat.SDK >= 12) {
wifiLockMode = WIFI_MODE_FULL_HIGH_PERF;
}
mWifiLock = wm.createWifiLock(wifiLockMode, TermDebug.LOG_TAG);
ActionBarCompat actionBar = ActivityCompat.getActionBar(this);
if (actionBar != null) {
mActionBar = actionBar;
actionBar.setNavigationMode(ActionBarCompat.NAVIGATION_MODE_LIST);
actionBar.setDisplayOptions(0, ActionBarCompat.DISPLAY_SHOW_TITLE);
if (mActionBarMode == TermSettings.ACTION_BAR_MODE_HIDES) {
actionBar.hide();
}
}
mHaveFullHwKeyboard = checkHaveFullHwKeyboard(getResources().getConfiguration());
updatePrefs();
mAlreadyStarted = true;
}
private String makePathFromBundle(Bundle extras) {
if (extras == null || extras.size() == 0) {
return "";
}
String[] keys = new String[extras.size()];
keys = extras.keySet().toArray(keys);
Collator collator = Collator.getInstance(Locale.US);
Arrays.sort(keys, collator);
StringBuilder path = new StringBuilder();
for (String key : keys) {
String dir = extras.getString(key);
if (dir != null && !dir.equals("")) {
path.append(dir);
path.append(":");
}
}
return path.substring(0, path.length()-1);
}
private void populateViewFlipper() {
if (mTermService != null) {
mTermSessions = mTermService.getSessions();
mTermSessions.addCallback(this);
if (mTermSessions.size() == 0) {
mTermSessions.add(createTermSession());
}
for (TermSession session : mTermSessions) {
EmulatorView view = createEmulatorView(session);
mViewFlipper.addView(view);
}
updatePrefs();
Intent intent = getIntent();
int flags = intent.getFlags();
String action = intent.getAction();
if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0 &&
action != null) {
if (action.equals(RemoteInterface.PRIVACT_OPEN_NEW_WINDOW)) {
mViewFlipper.setDisplayedChild(mTermSessions.size()-1);
} else if (action.equals(RemoteInterface.PRIVACT_SWITCH_WINDOW)) {
int target = intent.getIntExtra(RemoteInterface.PRIVEXTRA_TARGET_WINDOW, -1);
if (target >= 0) {
mViewFlipper.setDisplayedChild(target);
}
}
}
mViewFlipper.resumeCurrentView();
}
}
private void populateWindowList() {
if (mActionBar == null) {
// Not needed
return;
}
if (mTermSessions != null) {
int position = mViewFlipper.getDisplayedChild();
WindowListAdapter adapter = mWinListAdapter;
if (adapter == null) {
adapter = new WindowListActionBarAdapter(mTermSessions);
mWinListAdapter = adapter;
SessionList sessions = mTermSessions;
sessions.addCallback(adapter);
sessions.addTitleChangedListener(adapter);
mViewFlipper.addCallback(adapter);
mActionBar.setListNavigationCallbacks(adapter, mWinListItemSelected);
} else {
adapter.setSessions(mTermSessions);
}
mActionBar.setSelectedNavigationItem(position);
}
}
@Override
public void onDestroy() {
super.onDestroy();
mViewFlipper.removeAllViews();
unbindService(mTSConnection);
if (mStopServiceOnFinish) {
stopService(TSIntent);
}
mTermService = null;
mTSConnection = null;
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
if (mWifiLock.isHeld()) {
mWifiLock.release();
}
}
private void restart() {
startActivity(getIntent());
finish();
}
protected static TermSession createTermSession(Context context, TermSettings settings, String initialCommand) {
ShellTermSession session = new ShellTermSession(settings, initialCommand);
session.setProcessExitMessage(context.getString(R.string.process_exit_message));
return session;
}
private TermSession createTermSession() {
TermSettings settings = mSettings;
TermSession session = createTermSession(this, settings, settings.getInitialCommand());
session.setFinishCallback(mTermService);
return session;
}
private TermView createEmulatorView(TermSession session) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
TermView emulatorView = new TermView(this, session, metrics);
emulatorView.setExtGestureListener(new EmulatorViewGestureListener(emulatorView));
emulatorView.setOnKeyListener(mKeyListener);
registerForContextMenu(emulatorView);
return emulatorView;
}
private EmulatorView getCurrentEmulatorView() {
return (EmulatorView) mViewFlipper.getCurrentView();
}
private void updatePrefs() {
mUseKeyboardShortcuts = mSettings.getUseKeyboardShortcutsFlag();
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mViewFlipper.updatePrefs(mSettings);
for (View v : mViewFlipper) {
((EmulatorView) v).setDensity(metrics);
((TermView) v).updatePrefs(mSettings);
}
if (mTermSessions != null) {
for (TermSession session : mTermSessions) {
((ShellTermSession) session).updatePrefs(mSettings);
}
}
{
Window win = getWindow();
WindowManager.LayoutParams params = win.getAttributes();
final int FULLSCREEN = WindowManager.LayoutParams.FLAG_FULLSCREEN;
int desiredFlag = mSettings.showStatusBar() ? 0 : FULLSCREEN;
if (desiredFlag != (params.flags & FULLSCREEN) || (AndroidCompat.SDK >= 11 && mActionBarMode != mSettings.actionBarMode())) {
if (mAlreadyStarted) {
restart();
} else {
win.setFlags(desiredFlag, FULLSCREEN);
if (mActionBarMode == TermSettings.ACTION_BAR_MODE_HIDES) {
mActionBar.hide();
}
}
}
}
int orientation = mSettings.getScreenOrientation();
int o = 0;
if (orientation == 0) {
o = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
} else if (orientation == 1) {
o = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
} else if (orientation == 2) {
o = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
} else {
}
setRequestedOrientation(o);
}
@Override
public void onResume() {
super.onResume();
SessionList sessions = mTermSessions;
TermViewFlipper viewFlipper = mViewFlipper;
if (sessions != null) {
sessions.addCallback(this);
WindowListAdapter adapter = mWinListAdapter;
if (adapter != null) {
sessions.addCallback(adapter);
sessions.addTitleChangedListener(adapter);
viewFlipper.addCallback(adapter);
}
}
if (sessions != null && sessions.size() < viewFlipper.getChildCount()) {
for (int i = 0; i < viewFlipper.getChildCount(); ++i) {
EmulatorView v = (EmulatorView) viewFlipper.getChildAt(i);
if (!sessions.contains(v.getTermSession())) {
v.onPause();
viewFlipper.removeView(v);
--i;
}
}
}
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = mPrefs.edit();
String defValue = getDir("HOME", MODE_PRIVATE).getAbsolutePath();
String homePath = mPrefs.getString("home_path", defValue);
editor.putString("home_path", homePath);
editor.commit();
mSettings.readPrefs(mPrefs);
updatePrefs();
if (onResumeSelectWindow >= 0) {
viewFlipper.setDisplayedChild(onResumeSelectWindow);
onResumeSelectWindow = -1;
}
viewFlipper.onResume();
}
@Override
public void onPause() {
super.onPause();
SessionList sessions = mTermSessions;
TermViewFlipper viewFlipper = mViewFlipper;
viewFlipper.onPause();
if (sessions != null) {
sessions.removeCallback(this);
WindowListAdapter adapter = mWinListAdapter;
if (adapter != null) {
sessions.removeCallback(adapter);
sessions.removeTitleChangedListener(adapter);
viewFlipper.removeCallback(adapter);
}
}
if (AndroidCompat.SDK < 5) {
mBackKeyPressed = false;
}
final IBinder token = viewFlipper.getWindowToken();
new Thread() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(token, 0);
}
}.start();
}
private boolean checkHaveFullHwKeyboard(Configuration c) {
return (c.keyboard == Configuration.KEYBOARD_QWERTY) &&
(c.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mHaveFullHwKeyboard = checkHaveFullHwKeyboard(newConfig);
EmulatorView v = (EmulatorView) mViewFlipper.getCurrentView();
if (v != null) {
v.updateSize(false);
}
if (mWinListAdapter != null) {
mWinListAdapter.notifyDataSetChanged();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItemCompat.setShowAsAction(menu.findItem(R.id.menu_new_window), MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_new_window) {
doCreateNewWindow();
}
if (mActionBarMode == TermSettings.ACTION_BAR_MODE_HIDES) {
mActionBar.hide();
}
return super.onOptionsItemSelected(item);
}
private void doCreateNewWindow() {
if (mTermSessions == null) {
Log.w(TermDebug.LOG_TAG, "Couldn't create new window because mTermSessions == null");
return;
}
TermSession session = createTermSession();
mTermSessions.add(session);
TermView view = createEmulatorView(session);
view.updatePrefs(mSettings);
mViewFlipper.addView(view);
mViewFlipper.setDisplayedChild(mViewFlipper.getChildCount()-1);
}
@Override
protected void onActivityResult(int request, int result, Intent data) {
switch (request) {
case REQUEST_CHOOSE_WINDOW:
if (result == RESULT_OK && data != null) {
int position = data.getIntExtra(EXTRA_WINDOW_ID, -2);
if (position >= 0) {
onResumeSelectWindow = position;
} else if (position == -1) {
doCreateNewWindow();
onResumeSelectWindow = mTermSessions.size() - 1;
}
} else {
if (mTermSessions == null || mTermSessions.size() == 0) {
mStopServiceOnFinish = true;
finish();
}
}
break;
}
}
@Override
protected void onNewIntent(Intent intent) {
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
return;
}
String action = intent.getAction();
if (action == null) {
return;
}
if (action.equals(RemoteInterface.PRIVACT_OPEN_NEW_WINDOW)) {
// New session was created, add an EmulatorView to match
SessionList sessions = mTermSessions;
if (sessions == null) {
// Presumably populateViewFlipper() will do this later ...
return;
}
int position = sessions.size() - 1;
TermSession session = sessions.get(position);
EmulatorView view = createEmulatorView(session);
mViewFlipper.addView(view);
onResumeSelectWindow = position;
} else if (action.equals(RemoteInterface.PRIVACT_SWITCH_WINDOW)) {
int target = intent.getIntExtra(RemoteInterface.PRIVEXTRA_TARGET_WINDOW, -1);
if (target >= 0) {
onResumeSelectWindow = target;
}
}
}
private void doToggleSoftKeyboard() {
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
}
private void doToggleActionBar() {
ActionBarCompat bar = mActionBar;
if (bar == null) {
return;
}
if (bar.isShowing()) {
bar.hide();
} else {
bar.show();
}
}
private void doUIToggle(int x, int y, int width, int height) {
switch (mActionBarMode) {
case TermSettings.ACTION_BAR_MODE_NONE:
if (AndroidCompat.SDK >= 11 && (mHaveFullHwKeyboard || y < height / 2)) {
openOptionsMenu();
return;
} else {
doToggleSoftKeyboard();
}
break;
case TermSettings.ACTION_BAR_MODE_ALWAYS_VISIBLE:
if (!mHaveFullHwKeyboard) {
doToggleSoftKeyboard();
}
break;
case TermSettings.ACTION_BAR_MODE_HIDES:
if (mHaveFullHwKeyboard || y < height / 2) {
doToggleActionBar();
return;
} else {
doToggleSoftKeyboard();
}
break;
}
getCurrentEmulatorView().requestFocus();
}
private void execURL(String link)
{
Uri webLink = Uri.parse(link);
Intent openLink = new Intent(Intent.ACTION_VIEW, webLink);
PackageManager pm = getPackageManager();
List<ResolveInfo> handlers = pm.queryIntentActivities(openLink, 0);
if(handlers.size() > 0)
startActivity(openLink);
}
}
这是我的xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="90dp"
android:text="Button" />
</RelativeLayout>
请帮帮我。谢谢!
答案 0 :(得分:-1)
您的按钮缺少onClick字段。
```
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="90dp"
android:onClick="onClick" <!-- Add this line of code with correct onClick method -->
android:text="Button" />
```
查看android pages以获取更多相关信息。还要查看udacity课程以获取Android开发以及coursera课程。它们都非常适合学习android开发的基础知识。我已经完成了udacity课程并且不是太糟糕。我也听过关于课程的好消息。祝你好运!