2015-02-16 4 views
-1

Добрый день,Android Несколько намерений - одна форма

Я пытаюсь создать базовое меню в моем приложении andorid, которое содержит 5 кнопок, каждый из которых приведет вас в другую форму. Я пытаюсь создать Java, чтобы выполнить это действие, но по всей видимости, работает в следующее сообщение об ошибке с каждым из моих кнопок

«Пример не может быть решена в качестве переменной»

Пожалуйста, помогите мне в решении мой код, или если есть более простой способ, чтобы позволить мне выполнить это меню с 5 кнопок в каждой из них в другой форме

<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.techblogon.loginexample.MainMenu" > 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:src="@drawable/pic" /> 

    <Button 
     android:id="@+id/btnFootball" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/imageView1" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="25dp" 
     android:text="Football" 
     android:onClick="btnFootball" /> 

    <Button 
     android:id="@+id/btnHockey" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/btnFootball" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="25dp" 
     android:text="Hockey" 
     android:onClick="btnHockey" /> 

    <Button 
     android:id="@+id/btnLacrosse" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/btnLacrosse" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="25dp" 
     android:text="Lacrosse" 
     android:onClick="btnLacrosse" /> 

    <Button 
     android:id="@+id/btnCurling" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/btnLacrosse" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="25dp" 
     android:text="Curling" 
     android:onClick="btnCurling" /> 

    <Button 
     android:id="@+id/btnLogout" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/btnCurling" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="25dp" 
     android:text="Logout" 
     android:onClick="btnLogout" /> 

</RelativeLayout> 

Вот это Java:

package com.techblogon.loginexample; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.view.View.OnClickListener; 
import android.content.Context; 
import android.view.Menu; 
import android.view.MenuItem; 


public class MainMenu extends Activity { 

    public void ButtonOnClick(View v) { 
     switch (v.getId()) { 
      case R.id.btnFootball: 
      startActivity(Football); 
      break; 
      case R.id.btnHockey: 
       startActivity(Hockey); 
      break; 
      case R.id.btnLacrosse: 
       startActivity(Lacrosse); 
       break; 
      case R.id.btnCurling: 
       startActivity(Curling); 
       break; 
      case R.id.btnLogout: 
       startActivity(HomeActivity); 
       break; 
      } 
    } 


    } 
+0

Вам необходимо прочитать о намерениях и о том, как их запускать. –

+0

Возможный дубликат [Несколько намерений в главном меню] (http://stackoverflow.com/questions/28410768/multiple-intents-on-main-menu) – miselking

+0

Это ваш код или [это] (http: // stackoverflow.com/questions/28410768/multiple-intents-on-main-menu) ваш код? Мне кажется, что вы снова и снова задаете одни и те же вещи ... – miselking

ответ

1

@ Meryl2 Когда у используется "" андроид: OnClick = "btnLogout" ""

Тогда вы должны иметь метод общественности соответствующий void btnLogout (Просмотреть вид { // ваш код здесь }

То же самое относится ко всем кнопкам в вашем коде

1

Ваши ошибки ->

Вы не использовали setcontentView() или вы переопределили onCreate() метод. Еще одна вещь: вы не отправляете intent правильно.

Вот как вы можете отправить Intent

Intent intent = new Intent(getApplicationContext(), DestinationActivity.class); 
startActivity(intent); 
+0

Благодарим всех вас за отзыв всем, кого я действительно ценю всю вашу помощь и совет, когда я приступаю к новому языку программирования. Я решил использовать пользовательский подход @WannaGetHigh к проблеме, и теперь он работает правильно! – meryl2

0

Попробуйте этот код;

public class MainMenu extends Activity implements OnClickListener { 
Button btn_football,btn_hokey,btn_something; // add another button here 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.yourlayout); 
    btn_football = (Button)findViewById(R.id.btnFootball); 
    // add another button here same way 
    btn_football.setOnClickListener(this); 
    // add another button here same way 
    @Override 
public void onClick(View v) { 
    // TODO Auto-generated method stub 
    switch(v.getId()){ 
    case R.id.btnFootball: 
     Intent intent = new Intent(MainMenu.this,(nextclass_addhere).class); 
     startActivity(intent); 
     break; 
    case R.id.another button: 
     Intent intent = new Intent(MainMenu.this,(nextclass_addhere).class); 
     startActivity(intent); 
    break; 
    //.......add here another button with same way 
} 

} 

} 
1

Я изменил класс и макет. Вам нужно создать другие классы для каждого действия.

public class MainActivity extends Activity implements Button.OnClickListener{ 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


} 

@Override 
public void onClick(View v) { 
    int id = v.getId(); 

    Intent intent = null; 
    if(id == R.id.btnHockey) { 
     intent = new Intent(MainActivity.this, Hockey.class); 
    } else if(id == R.id.btnCurling) { 
     intent = new Intent(MainActivity.this, Curling.class); 
    } else if(id == R.id.btnFootball) { 
     intent = new Intent(MainActivity.this, Football.class); 
    } else if(id == R.id.btnLogout) { 
     intent = new Intent(MainActivity.this, Logout.class); 
    } else if(id == R.id.btnLacrosse) { 
     intent = new Intent(MainActivity.this, Lacrosse.class); 
    } 

    startActivity(intent); 
} 

}

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<ImageView 
    android:id="@+id/imageView1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true"/> 

<Button 
    android:id="@+id/btnFootball" 
    android:layout_below="@id/imageView1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="25dp" 
    android:text="Football" 
    android:onClick="onClick" /> 

<Button 
    android:id="@+id/btnHockey" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/btnFootball" 
    android:layout_marginTop="25dp" 
    android:text="Hockey" 
    android:onClick="onClick" /> 

<Button 
    android:id="@+id/btnLacrosse" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/btnHockey" 
    android:layout_marginTop="25dp" 
    android:text="Lacrosse" 
    android:onClick="onClick" /> 

<Button 
    android:id="@+id/btnCurling" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/btnLacrosse" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="25dp" 
    android:text="Curling" 
    android:onClick="onClick" /> 

<Button 
    android:id="@+id/btnLogout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/btnCurling" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="25dp" 
    android:text="Logout" 
    android:onClick="onClick" /> 

1

Думаю, у меня возникла ваша проблема. В каждой кнопки вы установите имя метода, который будет использоваться при нажатии на нее:

андроида: OnClick = "btnCurling"

андроида: OnClick = "btnHockey"

.. ,

Но у вас есть только один метод здесь, который:

public void ButtonOnClick(View v) { 
    ... 
} 

Одно из решений состоит в определении каждого метода следующим образом:

public class MainMenu extends Activity { 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // here you tell your activity what layout he will display 
     setContentView(R.layout.TheNameOfYourLayout); 
    } 

    // it will get there when you click on the "@+id/btnHockey" Button 
    public void btnHockey(View v) { 
     Intent intent = new Intent(this, NameOfTheActivityToLaunch.class); 
     startActivity(intent); 
    } 

    // then you add the other ones btnCurling, ... 
} 

Другим решением является автоматически установите слушатель каждой кнопки:

public class MainMenu extends Activity implements View.OnClickListener { 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // Here you tell your activity what layout he will display 
     setContentView(R.layout.TheNameOfYourLayout); 

     // This will find your button in the layout you just set 
     // and then set this Class as your Listener 
     findViewById(R.id.btnFootball).setOnClickListener(this); 

     // Then set the listener of all your other buttons 
    } 

    @Override 
    public void onClick(View v) { 

     switch (v.getId()) { 
      case R.id.btnFootball: 
       Intent intent = new Intent(this, NameOfTheActivityToLaunch.class); 
       startActivity(intent); 
       break; 
      case R.id.btnHockey: 
       Intent intent = new Intent(this, NameOfTheActivityToLaunch.class); 
       startActivity(intent); 
       break; 

      // ... 
     } 
    } 
} 

Вы также должны удалить всю строку android:onClick="btnCurling" в свой файл макета XML, чтобы это решение работало.

Надеюсь, что он помогает приветствиям :)

Смежные вопросы