如何使用按钮从一个Activity移动到另一个Activity?

时间:2014-10-11 12:23:47

标签: java android android-intent android-activity move

我尝试使用按钮从一个活动移动到另一个活动(使用下面提到的意图代码)。问题是,我不能。

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>

6 个答案:

答案 0 :(得分:1)

将它放在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);

}   };

答案 1 :(得分:0)

https://developer.android.com/training/basics/firstapp/starting-activity.html#StartActivity

删除它

setContentView(R.layout.activity_login);

来自

public void onClick(View v)

答案 2 :(得分:0)

很抱歉,最后一个答案将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

答案 3 :(得分:0)

删除行

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"
/>

答案 4 :(得分:0)

为什么你不能在MainActivity中使用这样的东西?

Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {

    Intent i = new Intent(getApplicationContext(),GoogleDocsLogin.class);
    startActivity(i);
});

答案 5 :(得分:0)

你的第一项活动应该是,

 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);
}