2015-07-14 6 views
2

Я действительно новичок в программировании на Android, и я застрял с очень маленькой проблемой в своем приложении. Приложение (очень простое) почти готово, его просто, что есть кнопка, и когда она нажата, я хочу, чтобы пользователь получил ответ в виде сообщения или некоторой анимации, чтобы пользователь мог почувствовать, что приложение зарегистрировал нажатие кнопки. Я искал и пытался выполнить stackoverflow и другие учебники, но безрезультатно. Я просто хочу какой-то ответ при нажатии кнопки, чтобы пользователь не смущался о том, работает ли приложение или нет. Любая помощь будет оценена!! Вот код ниже: -Android отображает всплывающее сообщение или анимацию при нажатии кнопки

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:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MyActivity" 
    android:background="#d1000000"> 


    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Click Me" 
     android:id="@+id/Hinglishbutton" 
     android:background="#cfa16cff" 
     android:hapticFeedbackEnabled="true" 
     android:onClick="buttonHandler" 
     android:clickable="true" 
     android:textColor="#a5fafbf9" 
     tools:ignore="HardcodedText" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginBottom="71dp" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:text="Welcome to Hinglish :)" 
     android:id="@+id/textView4" 
     android:textColor="#a5fafbf9" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="62dp" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Hinglish lets you add Hindi words to your predictive dictionary thus enabling a richer typing experience!" 
     android:id="@+id/textView" 
     android:textColor="#a5fafbf9" 
     android:textIsSelectable="false" 
     android:textSize="14sp" 
     android:typeface="sans" 
     android:layout_marginTop="80dp" 
     android:layout_below="@+id/textView4" 
     android:layout_centerHorizontal="true" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Click the button once, minimize Hinglish and go grab a coffee. You will now be able to type hindi words without autocorrect converting them to junk english!" 
     android:id="@+id/textView2" 
     android:textColor="#a5fafbf9" 
     android:textIsSelectable="false" 
     android:textSize="14sp" 
     android:typeface="sans" 
     android:layout_centerVertical="true" 
     android:layout_centerHorizontal="true" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceSmall" 
     android:text="Hosting this app costs money! To pitch in, contact the developer at [email protected] :) :)" 
     android:id="@+id/textView5" 
     android:textColor="#a5fafbf9" 
     android:layout_below="@+id/textView2" 
     android:layout_alignRight="@+id/textView2" 
     android:layout_alignEnd="@+id/textView2" 
     android:layout_marginTop="43dp" /> 


</RelativeLayout> 

myActivity.java файл: -

package com.example.spandanmadan1.hinglish; 

import android.content.res.AssetManager; 
import android.provider.UserDictionary; 
import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.animation.Animation; 
import android.view.animation.AnimationUtils; 
import android.widget.Button; 
import android.widget.Toast; 

import java.io.BufferedReader; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 


public class MyActivity extends ActionBarActivity { 

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


     Button bsubmit = (Button) findViewById(R.id.Hinglishbutton); 

     bsubmit.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Toast.makeText(getApplicationContext(), "Thank you for using Hinglish", Toast.LENGTH_LONG).show(); 
       InputStream fis = getResources().openRawResource(R.raw.hindislang); 
       BufferedReader bfr = null; 
       try { 
        bfr = new BufferedReader(new InputStreamReader(fis)); 
        String line = null; 
        while ((line = bfr.readLine()) != null) { 
         UserDictionary.Words.addWord(getApplicationContext(), line, 1, "", null); 
        } 
       } catch (IOException ex) { 
        ex.printStackTrace(); 
       } 
      } 
     }); 
    } 

    @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_my, 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); 
    } 
} 

ответ

2

Вы можете использовать Toast:

Toast.makeText(getApplicationContext(),"<Your message to the User>",Toast.LENGTH_SHORT).show(); 

сообщение будет показано при нажатии кнопки.

+0

Привет, я попробовал, но не работал! Нужно ли мне обновить код выше, чтобы показать новый java-файл! Пожалуйста, взгляните на это :) –

+0

Я не уверен, если это проблема, но проверьте это. Вы указали: android: onClick = "buttonHandler" ie. это функция, ожидаемая при нажатии кнопки. Почему бы вам не дать тост внутри buttonHandler (View view)? Или удалите свойство onClick из вашего xml и повторите попытку. – aashima

+0

Пожалуйста, дайте мне знать, если это помогло .. – aashima

3

Я создал новый проект, использовали свой XML и в функции buttonHandler я дал тост следующим образом:

import android.os.Bundle; 
import android.support.v7.app.ActionBarActivity; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Toast; 


public class MyActivity extends ActionBarActivity { 

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

public void buttonHandler(View view) { 
    Toast.makeText(getApplicationContext(), "Thank you for using Hinglish", Toast.LENGTH_LONG).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_my, 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); 
} 
} 

Это работает. Тост: «Спасибо, что использовал Hinglish», был показан на экране.

+0

Привет, aashima, спасибо за ваш ответ. Спасибо за ваш ответ, я выяснил, в чем проблема. В тот момент, когда я комментирую цикл while в моем коде, тост работает Итак, теперь еще не видно, как я могу заставить их работать вместе! :) –

+0

:) удачи с вашим приложением – aashima

+0

Спасибо за вашу помощь :) –

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