2014-10-11 154 views
0

我試圖從一個活動轉移到另一個使用按鈕(使用下面提到的意圖代碼)。問題是,我不能。如何使用按鈕從一個活動移動到另一個活動?

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> 
+0

公共無效的onClick(視圖v)在MainActivity應與按鈕關聯。但從你給它的代碼沒有關聯到任何按鈕。 – worldofprasanna 2014-10-11 12:26:22

+0

發表您的 「activity_main.xml中」 – Harshad07 2014-10-11 12:26:34

+0

分享您layoutcode – Amy 2014-10-11 12:27:01

回答

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

} }; 
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 
+0

錯誤:View類型中的setOnClickListener(View.OnClickListener)方法不適用於應用此代碼的參數(MainActivity) – Dhairyadev 2014-10-11 12:33:11

+0

? – Amy 2014-10-11 12:33:59

+0

我只在那裏粘貼。但後來我刪除了最後一行,它的工作。謝謝。現在我怎麼能添加一個鏈接到webView? – Dhairyadev 2014-10-11 12:44:25

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

@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

+0

謝謝,但它現在工作。 :)任何方式來添加一個鏈接到webView? – Dhairyadev 2014-10-11 12:46:12

+0

'webView.loadUrl(「http://this.url.is.loaded.com」);' – EpicPandaForce 2014-10-11 12:59:46

0

爲什麼你不能使用在MainActivity這樣的事情?

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

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

這給了我一堆的錯誤。 :( – Dhairyadev 2014-10-11 12:39:17

+0

什麼是錯誤? – worldofprasanna 2014-10-11 12:44:49

+0

現在沒有錯誤,我修好了。現在工作。謝謝。:) – Dhairyadev 2014-10-11 12:45:23

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); 
} 
相關問題