如何使用按钮从一个活动移动到另一个活动?
我试图从一个活动转移到另一个使用按钮(使用下面提到的意图代码)。问题是,我不能。如何使用按钮从一个活动移动到另一个活动?
MainActivity.java:
package com.webding.gateway14;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.content.Intent;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(),GoogleDocsLogin.class);
startActivity(i);
setContentView(R.layout.activity_login);
}
}; ;
的Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.webding.gateway14"
android:installLocation="auto"
android:versionCode="1"
android:versionName="1.0.24" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".GoogleDocsLogin"
android:label="@string/title_activity_google_docs_login" >
</activity>
</application>
</manifest>
GoogleDocsLogin.java(第二活性):
package com.webding.gateway14;
import java.net.URL;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.content.Intent;
public class GoogleDocsLogin extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.google_docs_login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try {
URL urlObj = new URL(url);
// The popular Google forms URL shortener has
// been modified here to get Stack Overflow to
// accept it
if(TextUtils.equals(urlObj.getHost(),"http://boo.gl/forms/VftZnVjaCr")) {
//Allow the WebView in your application to do its thing
return false;
} else {
//Pass it to the system, doesn't match your domain
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
//Tell the WebView you took care of it.
return true;
}
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
activity_main.xml中:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.webding.gateway14.MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp"
android:text="@string/next" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="8dp"
android:text="@string/copyright"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView6"
android:layout_marginTop="26dp"
android:text="@string/mfs"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/textView1"
android:layout_marginRight="52dp"
android:layout_marginTop="51dp"
android:text="@string/gway"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/textView2"
android:layout_marginTop="25dp"
android:text="@string/presented"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView2"
android:layout_below="@+id/textView4"
android:layout_marginTop="28dp"
android:text="@string/cclub"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView3"
android:layout_marginTop="89dp"
android:text="@string/cc"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
把这个onCreate方法会做
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{ Intent i = new Intent(getApplicationContext(),GoogleDocsLogin.class);
startActivity(i);
} };
https://developer.android.com/training/basics/firstapp/starting-activity.html#StartActivity
删除它
setContentView(R.layout.activity_login);
从
public void onClick(View v)
仍然无法正常工作。 :/ – Dhairyadev 2014-10-11 12:31:43
哦,对不起。您应该执行以下操作:http://stackoverflow.com/a/26314776 – WidWing 2014-10-11 12:43:26
对不起,最后的答案中添加的onClick功能的XML文件
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp"
android:text="@string/next"
android:onClick="onClick" /> // Add this line
错误:View类型中的setOnClickListener(View.OnClickListener)方法不适用于应用此代码的参数(MainActivity) – Dhairyadev 2014-10-11 12:33:11
? – Amy 2014-10-11 12:33:59
我只在那里粘贴。但后来我删除了最后一行,它的工作。谢谢。现在我怎么能添加一个链接到webView? – Dhairyadev 2014-10-11 12:44:25
删除线
setContentView(R.layout.activity_login);
从
public void onClick(View v)
在XML布局
此外,指定的onClick方法
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp"
android:text="@string/next"
android:onClick="onClick" />
另一种可能的替代方案是以下内容:
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
...
@Override
public void onCreate(Bundle bundle)
{
super(bundle);
...
button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(this);
...
}
@Override
public void onClick(View v)
{
if(v == button)
{
Intent i = new Intent(this, OtherActivity.class);
startActivity(i);
}
}
}
或者另一种选择:
public class MainActivity extends ActionBarActivity {
...
@Override
public void onCreate(Bundle bundle)
{
super(bundle);
...
button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Intent i = new Intent(MainActivity.this, OtherActivity.class);
MainActivity.this.startActivity(i);
}
});
}
}
编辑
的WebView代码:
@SuppressLint("SetJavaScriptEnabled")
public class WebViewActivity extends Activity
{
private WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_webview);
myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.setWebChromeClient(new MyWebChromeClient());
//myWebView.addJavascriptInterface(new WebAppInterface(this.getApplicationContext()), "Android");
myWebView.loadUrl("http://put.url.here");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
{
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.activity_webview, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
if (item.getItemId() == R.id.clear_cache)
{
Toast.makeText(this.getApplicationContext(), "Cache cleared.", Toast.LENGTH_SHORT).show();
myWebView.clearCache(true);
}
return super.onMenuItemSelected(featureId, item);
}
private class MyWebViewClient extends WebViewClient
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (Uri.parse(url).getHost().equals("the.original.site.url"))
{
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
private class MyWebChromeClient extends WebChromeClient
{
@Override
public boolean onJsAlert(WebView view, String url, String message,
final android.webkit.JsResult result)
{
new AlertDialog.Builder(WebViewActivity.this).setTitle(R.string.title_dialog_alert)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result)
{
new AlertDialog.Builder(WebViewActivity.this).setTitle(R.string.title_dialog_confirm)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(WebViewActivity.this.getApplicationContext(), "Confirmed.",
Toast.LENGTH_SHORT).show();
result.confirm();
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(WebViewActivity.this.getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
result.cancel();
}
}).create().show();
return true;
}
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
final JsPromptResult result)
{
final LayoutInflater factory = LayoutInflater.from(WebViewActivity.this);
final View v = factory.inflate(R.layout.javascript_prompt_dialog, null);
((TextView) v.findViewById(R.id.prompt_message_text)).setText(message);
((EditText) v.findViewById(R.id.prompt_input_field)).setText(defaultValue);
new AlertDialog.Builder(WebViewActivity.this).setTitle(R.string.title_dialog_prompt)
.setView(v)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
String value = ((EditText) v.findViewById(R.id.prompt_input_field))
.getText().toString();
Toast.makeText(WebViewActivity.this.getApplicationContext(),
"Confirmed: " + value, Toast.LENGTH_SHORT).show();
result.confirm(value);
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(WebViewActivity.this.getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
result.cancel();
}
}).setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
Toast.makeText(WebViewActivity.this.getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
result.cancel();
}
}).show();
return true;
};
@Override
public void onProgressChanged(WebView view, int newProgress)
{
updateProgress(newProgress);
super.onProgressChanged(view, newProgress);
}
@Override
public void onReceivedTitle(WebView view, String title)
{
setTitle(title);
super.onReceivedTitle(view, title);
}
}
}
布局:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
@Dhairyadev试试这个,如果还是看不懂http://codereview.stackexchange.com/questions/57543/why-does-the-new-adt-create-a- static-inner-class-fragment-by-default – EpicPandaForce 2014-10-11 12:39:43
谢谢,但它现在工作。 :)任何方式来添加一个链接到webView? – Dhairyadev 2014-10-11 12:46:12
'webView.loadUrl(“http://this.url.is.loaded.com”);' – EpicPandaForce 2014-10-11 12:59:46
为什么你不能使用在MainActivity
这样的事情?
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
Intent i = new Intent(getApplicationContext(),GoogleDocsLogin.class);
startActivity(i);
});
这给了我一堆的错误。 :( – Dhairyadev 2014-10-11 12:39:17
什么是错误? – worldofprasanna 2014-10-11 12:44:49
现在没有错误,我修好了。现在工作。谢谢。:) – Dhairyadev 2014-10-11 12:45:23
你的第一个活动是应该的,
Button btn;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this , GoogleDocsLogin.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
公共无效的onClick(视图v)在MainActivity应与按钮关联。但从你给它的代码没有关联到任何按钮。 – worldofprasanna 2014-10-11 12:26:22
发表您的 “activity_main.xml中” – Harshad07 2014-10-11 12:26:34
分享您layoutcode – Amy 2014-10-11 12:27:01