【问题标题】:How to move from one Activity to another using a button?如何使用按钮从一个活动移动到另一个活动?
【发布时间】:2014-10-11 12:23:46
【问题描述】:

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

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>

【问题讨论】:

  • public void onClick(View v) in MainActivity 应该与一个按钮相关联。但是从您提供的代码来看,它与任何按钮都没有关联。
  • 发布您的“activity_main.xml”
  • 分享你的布局代码

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


【解决方案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);

}   };

【讨论】:

    【解决方案2】:

    抱歉最后一个答案在 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" /> // Add this line
    

    【讨论】:

    • 错误:View类型中的setOnClickListener(View.OnClickListener)方法不适用于参数(MainActivity)
    • 我只粘贴了那里。但后来我删除了最后一行,它起作用了。谢谢。现在如何添加到 webView 的链接?
    • 您必须在布局 .xml 文件中创建另一个 webview
    • 它需要 15+ 回购。
    • 我确实在 xml 文件中创建了另一个 webView,即 GoogleDocsLogin。如何在此处添加链接?
    【解决方案3】:

    你的第一个活动应该是,

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

    【讨论】:

      【解决方案4】:

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

      Button button = (Button) findViewById(R.id.button1);
      button.setOnClickListener(new OnClickListener() {
      
          Intent i = new Intent(getApplicationContext(),GoogleDocsLogin.class);
          startActivity(i);
      });
      

      【讨论】:

        【解决方案5】:

        删除线

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

        编辑

        网页浏览代码:

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

        【讨论】:

        【解决方案6】:

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

        删除它

        setContentView(R.layout.activity_login);
        

        来自

        public void onClick(View v)
        

        【讨论】:

          猜你喜欢
          • 2015-09-15
          • 2013-07-05
          • 1970-01-01
          • 1970-01-01
          • 2017-09-30
          • 1970-01-01
          • 1970-01-01
          • 2015-04-05
          • 1970-01-01
          相关资源
          最近更新 更多