2014-01-30 2 views
-1

Несколько раз подряд я следил за полными инструкциями по http://developer.android.com/training/basics/firstapp/creating-project.html и не мог начать свою деятельность. Приложение имеет текстовое поле и кнопку отправки. Когда я ввожу текст в текстовое поле и нажимаю кнопку отправки, необходимо запустить другое действие. Однако, с моим текущим кодом, нажатие кнопки отправки ничего не делает.Не могу начать какую-либо другую деятельность


MySecondApp/SRC/MainActivity.java


package com.example.mysecondapp; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.widget.EditText; 

public class MainActivity extends Activity { 
    public final static String EXTRA_MESSAGE = "com.example.mysecondapp.MESSAGE"; 

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

    /** Called when the user clicks the Send button */ 
    public void sendMessage(View view) { 
     Intent intent = new Intent(this, DisplayMessageActivity.class); 
     EditText editText = (EditText) findViewById(R.id.edit_message); 
     String message = editText.getText().toString(); 
     intent.putExtra(EXTRA_MESSAGE, message); 
     startActivity(intent); 
    } 

} 

MySecondApp/SRC/DisplayMessageActivity.java


package com.example.mysecondapp; 

import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.v4.app.NavUtils; 
import android.view.MenuItem; 
import android.widget.TextView; 

public class DisplayMessageActivity extends Activity { 

    @SuppressLint("NewApi") 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // Get the message from the intent 
     Intent intent = getIntent(); 
     String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 

     // Create the text view 
     TextView textView = new TextView(this); 
     textView.setTextSize(40); 
     textView.setText(message); 

     // Set the text view as the activity layout 
     setContentView(textView); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
     case android.R.id.home: 
      NavUtils.navigateUpFromSameTask(this); 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 
} 

MySecondApp/RES/макет/activity_main.xml


<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 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:orientation="horizontal" > 
     <EditText android:id="@+id/edit_message" 
      android:layout_weight="1" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:hint="@string/edit_message" /> 
     <Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="@string/button_send" /> 
      android:onClick="sendMessage" /> 
</LinearLayout> 

MySecondApp/RES/макет/activity_display_message.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=".DisplayMessageActivity" > 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 

</RelativeLayout> 

MySecondApp/RES/значения /strings.xml


<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <string name="app_name">Safe\'s First App</string> 
    <string name="edit_message">Enter a message</string> 
    <string name="button_send">Send</string> 
    <string name="action_settings">Settings</string> 
    <string name="title_activity_main">MainActivity</string> 
    <string name="title_activity_display_message">My Message</string> 
    <string name="hello_world">Hello world!</string> 

</resources> 

MySecondApp/AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.mysecondapp" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="18" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name="com.example.mysecondapp.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="com.example.mysecondapp.DisplayMessageActivity" 
      android:label="@string/title_activity_display_message" 
      android:parentActivityName="com.example.mysecondapp.MainActivity" > 
      <meta-data 
       android:name="android.support.PARENT_ACTIVITY" 
       android:value="com.example.mysecondapp.MainActivity" /> 
     </activity> 
    </application> 

</manifest> 
+0

Если вы внимательно посмотрите на свой манифест, вы заметите, что ваша функция DisplayMessageActivity не имеет декларации IntentFilter. – tolgap

+0

@tolgap Ему нужно включить IntentFilter в свой манифест для необходимых ему действий, поэтому в его основной деятельности есть IntentFilter, объявляя его своим главным. Его фактическая ошибка заключается в кнопке xml в MySecondApp/res/layout/activity_main.xml, как я уже отметил ниже – GrouchyPanda

+0

@ChrisM. Я действительно пропустил это, поскольку это упало за пределами представления приложения StackExchange. – tolgap

ответ

1

Ваша проблема заключается в XML для вашей первой деятельности. У вас есть два конечных символа в Button. Удалите /> после строки android: text.

+0

Ваши изменения в его сообщении были неверными. Это был не избыточный блок. Второй блок xml-кода показывал, чтобы убрать свойство 'android: onClick' со своим * вторым способом использования кода. –

1

Изменить Вы XML:

<Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="@string/button_send" /> 
      android:onClick="sendMessage" /> 

к:

<Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="@string/button_send" 
      android:onClick="sendMessage" /> 

А также, я думаю, вы должны ссылаться на вашу кнопку в OnCreate метод.

Вы также можете попытаться изменить ваш код:

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

public class Main extends Activity { 
    public final static String EXTRA_MESSAGE = "com.example.mysecondapp.MESSAGE"; 

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

     Button yourButton = (Button) findViewById(R.id.yourid); 

     yourButton.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       Intent intent = new Intent(Main.this, YourSecondActivity.class); 
       EditText editText = (EditText) findViewById(R.id.yourEditText); 
       String message = editText.getText().toString(); 
       intent.putExtra(EXTRA_MESSAGE, message); 
       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; 
    } 

} 

И Измени XML из:

<Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="@string/button_send" /> 
      android:onClick="sendMessage" /> 

To:

<Button 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="@string/button_send" 
       /> 
+0

Зачем вам нужно: public final static String EXTRA_MESSAGE = "com.example.mysecondapp.MESSAGE"; и, String message = editText.getText(). ToString(); intent.putExtra (EXTRA_MESSAGE, message); ? если вы намерены только начать новую деятельность – mike20132013

+0

Ссылка на кнопку в src и добавление onclicklistener не требуется, поскольку он уже объявляет действие onclick в своем xml. – GrouchyPanda

+0

Я понимаю ... но если он просто хочет начать еще одно действие при нажатии кнопки, зачем использовать дополнительный шаг? – mike20132013

0
<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/button_send" /> 
    android:onClick="sendMessage" /> 

Посмотрите, как последний линия черная?Это потому, что вы закончили кнопку тег дважды с />

Так возьмите закрывающий тег далеко на второй последней строке: android:text="@string/button_send"

и ваш код будет:

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/button_send" 
    android:onClick="sendMessage" /> 
0

При размещении в OnClick свойство и выберите sendMessage [MainActivity] из раскрывающегося списка в .xml файле: android: onClick = "sendMessage (MainActivity)". Удалить "(MainActivity)": Итак, в .xml файле: android: onClick = "sendMessage" И запустите приложение снова!

+0

Можете ли вы перефразировать свой ответ, это трудно понять. – codeepic

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