2015-11-29 4 views
0

Я пытаюсь создать приложение, которое при нажатии кнопки изменяет отображаемый текст. Однако это не сработает. Я проверил свой код, бит, я не вижу ничего плохого в моем обработчике событий. Вот мой код:Моя кнопка приложения не работает

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     //Reference Button 
     Button ekeButton = (Button)findViewById(R.id.ekeButton); 

     ekeButton.setOnClickListener(
       new View.OnClickListener() { 
        public void onClick(View view) { 
         TextView displayText = (TextView) findViewById(R.id.displayText); 
         displayText.setText(R.string.NewMassage); 

        } 
       } 
     ); 

     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
      } 
     });  
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.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(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
} 

Вот мой обновленный код:

package com.mesoft.eventhandler; 

import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     //Reference Button 
     Button ekeButton = (Button)findViewById(R.id.ekeButton); 
     final TextView displayText = (TextView) findViewById(R.id.displayText); 


     ekeButton.setOnClickListener(
       new View.OnClickListener() { 
        public void onClick(View view) { 
         displayText.setText(getString(R.string.NewMassage)); 

        } 
       } 
     ); 



     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
      } 
     }); 





    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.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(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
} 

и я объявил мою строку в моей string.xml Вот код:

<resources> 
    <string name="app_name">Event Handler</string> 
    <string name="action_settings">Settings</string> 
    <string name="click">Choose Massage</string> 
    <string name="ShowMassage">Merry Xmas</string> 
    <string name="NewMassage">Happy new year</string> 
</resources> 

здесь activity_main.xml код:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" 
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context=".MainActivity" 
    tools:showIn="@layout/activity_main"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:text="@string/ShowMassage" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="90dp" 
     android:id="@+id/displayText" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/click" 
     android:id="@+id/ekeButton" 
     android:layout_marginTop="74dp" 
     android:enabled="false" 
     android:layout_below="@+id/displayText" 
     android:layout_alignLeft="@+id/displayText" 
     android:layout_alignStart="@+id/displayText" 
     android:textColor="#090909" /> 
</RelativeLayout> 
+1

Какую ошибку вы получите за пределами? (если есть) –

+0

Используйте 'getResources(). getString (R.string.NewMassage)' вместо 'getString (R.string.NewMassage)' – Piyush

+0

удалите 'android: enabled =" false "' из вашего '

ответ

0

Заменить это,

displayText.setText(R.string.NewMassage); 

с

displayText.setText(getString(R.string.NewMassage)); 

А также,

Его лучше объявить

TextView displayText = (TextView) findViewById(R.id.displayText); 

вне onClick() метод. Я имею в виду под

Button ekeButton = (Button)findViewById(R.id.ekeButton); 

Примечание: убедитесь, что вы объявили NewMassage в strings.xml

<string name="NewMassage">Text you want to display</string> 
+0

Я заменил код так, как вы предлагали, и объявил «TextView» вне «onClick», но он все равно не работает. Я не знаю, что еще делать ... – ekeneduk

+0

Попробуйте заменить строку displayText слишком – activesince93

+0

с чем? или как его заменить – ekeneduk

0

Изменение этой линии

displayText.setText(R.string.NewMassage); 

с

displayText.setText(getResources().getString(R.string.NewMassage)); 

R.string.NewMassage возвращает идентификатор NewMassage Ресурс строки в виде Integer.

А также как сказал activesince93, объявить TextView кнопку OnclickListener

+0

ваша проблема решена? –

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