2016-06-25 3 views
-1

アンドロイド開発を始めたばかりで、引き出しをナビゲートするとアプリがクラッシュします。ナビゲーション・ドロワ・アクティビティで編集されたコードがあります。引き出しをナビゲートするときに私のアプリがクラッシュするのはなぜですか?

これは私が編集したもので、ドロワーからアイテムの1つを選択するときに新しいスクリーンが欲しかったです。私は3つの新しいレイアウト(xmlファイル)を作成し、あなたがsetContentView(R.layout.something)を使用することはできませんので、これらの

@SuppressWarnings("StatementWithEmptyBody") 
@Override 
public boolean onNavigationItemSelected(MenuItem item) { 
    // Handle navigation view item clicks here. 
    int id = item.getItemId(); 

    if (id == R.id.call) { 

     setContentView(R.layout.phone); 

     et1 = (EditText) findViewById(R.id.editText); 
     btn = (Button) findViewById(R.id.button1); 

     btn.setOnClickListener(this); 

    } 


    else if (id == R.id.message) { 

     setContentView(R.layout.sms); 

     et2 = (EditText) findViewById(R.id.editText2); 
     et3 = (EditText) findViewById(R.id.editText3); 
     btn2 = (Button) findViewById(R.id.button2); 

     btn2.setOnClickListener(this); 
    } 


    else if (id == R.id.email) { 

     setContentView(R.layout.email); 

     et4 = (EditText) findViewById(R.id.editText4); 
     et5 = (EditText) findViewById(R.id.editText5); 
     et6 = (EditText) findViewById(R.id.editText6); 

     btn3 = (Button)findViewById(R.id.button3); 


     btn3.setOnClickListener(this); 



    } 


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    drawer.closeDrawer(GravityCompat.START); 
    return true; 
} 
+3

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

、ここではあなたに、より理解しやすいかもしれないもう一つの例へのリンクであり、エラー番号 – Shank

+3

の 'setContentView'を悪用するべきではありません。使用フラグメント、それは彼らのために作られたものです。 –

答えて

2

アプリがクラッシュされて表示させたいです。

まず、XMLファイルごとにアクティビティを作成する必要があります。これは次のように簡単です:

public class Activity1 { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.phone); //DO THIS FOR EACH XML LAYOUT 
    } 
} 

次に、AndroidManifest.xmlに各アクティビティを追加することを忘れないでください。

<application 
    android:allowBackup="true" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme"> 
    <activity 
     android:name=".MainActivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    //ADD NEXT 2 LINES FOR EACH NEW ACTIVITY YOU MAKE 
    <activity 
     android:name=".Activity1"> 
</application 

次に、あなたがする必要がある最後の事はあなたのonNavigationItemSelected方法である:あなたのマニフェストファイルは、おそらくすでにこのような何かを持っています。

の代わりにsetContentView(R.layout.something)は、このような何か:私の答えでは不明な点がある場合は

Intent intent = new Intent(this, Activity1.class); 
startActivity(intent); 

を、お気軽に。

注:これは、アプリがナビゲーション・ドロワーを介してアクティビティーを変更するようにする場合です。別のアプローチのためにFragmentsを調べたいと思うかもしれません。

編集:ここでの活動にGoogleのチュートリアルへのリンクです:

http://hmkcode.com/android-start-another-activity-within-the-same-application/

+0

ありがとう、私はそれを学んだ。今それは動作します。同じケースで断片を扱うことも教えてください。 –

関連する問題