Получить текстовое значение кнопки динамически

#android

#Android

Вопрос:

Мое мнение

 <Button android:id="@ id/button1" android:text="Text 1"
android:layout_height="wrap_content"
                android:layout_width="fill_parent"></Button>

        <Button android:id="@ id/button2" android:text="Text 2"
android:layout_height="wrap_content"
                android:layout_width="fill_parent"></Button>

        <Button android:id="@ id/button3" android:text="Text 3"
android:layout_height="wrap_content"
                android:layout_width="fill_parent"></Button>

        <Button android:id="@ id/button4" android:text="Text 4"
android:layout_height="wrap_content"
                android:layout_width="fill_parent"></Button> 
  

У меня неопределенное количество кнопок, и мне нужно получить текст в событии касания.

Как я это делаю?

Много проблем.

Редактировать:

Спасибо за все, это результат ваших ответов => https://play.google.com/store/apps/details?id=br.com.redrails.torpedos Мое приложение: D

Ответ №1:

Если вы назовете все свои кнопки «button1, button2, button3 …», вы можете сделать это:

 for(int i = 1; i <= buttonCount; i  ) {
    int id = getResources().getIdentifier("button"   i, "id", getPackageName() );
    findViewById(id).setOnClickListener(this);
}
  

Где buttonCount количество кнопок, которые у вас есть. Этот метод будет помещен в onCreate() .

Затем для вашего onClick:

 public void onClick(View v) {
    if (v instanceof TextView) {
        CharSequence text = ((TextView) v).getText();
        // Do fun stuff with text
    }
}
  

Ваша деятельность должна будет реализовать OnClickListener

Комментарии:

1. Нет проблем … имейте в виду, что эта операция может быть очень медленной и не рекомендуется, если вы можете ее избежать.

Ответ №2:

Вы можете получить текст кнопки с помощью метода getText() .

Комментарии:

1. Да, но мне нужно получить идентификатор кнопки перед событием ontouch … как?

Ответ №3:

Вы можете сделать :

 Button button4= (Button) findViewById(R.id.button4);
text = button4.getText();
  

Ответ №4:

Вот полный пример:

 import android.os.Bundle;
import android.widget.Toast;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity implements OnClickListener
{
    private Button btn1, btn2, btn3, btn4; // You can add more if you like

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         btn1 = (Button) findViewByID(R.id.button1);
         btn2 = (Button) findViewByID(R.id.button2);
         btn3 = (Button) findViewByID(R.id.button3);
         btn4 = (Button) findViewByID(R.id.button4);
         // declare the other buttons if any

         btn1.setOnClickListener(this);
         btn2.setOnClickListener(this);
         btn3.setOnClickListener(this);
         btn4.setOnClickListener(this);
         // register the other buttons as well if any
    }

    @Override
    public void onClick(View v)
    {
        String text = ((Button) v).getText();
        Toast.makeText(this, "You clicked "   text , Toast.LENGTH_SHORT).show();
    }
}
  

Комментарии:

1. Очень неудобно, но я представляю, что кнопок сто… это не работает нормально =

2. конечно, вы можете включить другие кнопки, и это будет работать просто отлично.