Сделайте случайно сгенерированные кнопки ImageButtons кликабельными

1

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

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

Здесь my Main.java:

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final List<String> images = new ArrayList<String>();
        for (int i=1; i<=13; i++) {
            images.add("img"+i);
        }
        final Button imgView = (Button)findViewById(R.id.top1);
        String imgName = null;
        int id = 0;

        Collections.shuffle(images, new Random());
        imgName = images.remove(0);
        imageRandomizer(imgName, id, imgView);
   }

    public void imageRandomizer(String imgName, int id, final Button imgView) {
        id = getResources().getIdentifier(imgName, 
                                          "drawable",
                                          getPackageName());  
        imgView.setBackgroundResource(id);
    }

}

В моем макете я указал id top1 как Button. Таким образом, приведенный выше код будет выглядеть так, как показано на рисунках, которые имеют имена img1.jpg, img2.jpg, img3.jpg, пока img13.jpg.

Сделать ImageButton доступным для одного действия без зависящего от показанного случайного изображения легко, я могу сделать это без проблем. Но то, что я хочу сделать, это что-то вроде того, когда генерируется img1.jpg, он становится интерактивным и приводит к Activity1.java, для img2.jpg намерение переходит к Activity2.java и т.д.

ИЗМЕНИТЬ @Roflcoptr Здесь мой OnClickListener:

private OnClickListener top_listener = new OnClickListener() {
        public void onClick(View v) {
             switch((Integer) v.getTag()) {

             case 1: 
             Intent aid = new Intent(Main.this, ProjektAID.class);
             startActivity(aid);

             case 2:
             Intent adh = new Intent(Main.this, ProjektADH.class);
             startActivity(adh);

             case 3:
                 Intent bos = new Intent(Main.this, ProjektBOS.class);
                 startActivity(bos);

             case 4:
                 Intent brot = new Intent(Main.this, ProjektBROT.class);
                 startActivity(brot);

             case 5:
                 Intent care = new Intent(Main.this, ProjektCARE.class);
                 startActivity(care);

             case 6:
                 Intent caritas = new Intent(Main.this, ProjektCARITAS.class);
                 startActivity(caritas);

             case 7:
                 Intent doc = new Intent(Main.this, ProjektDOC.class);
                 startActivity(doc);

             case 8:
                 Intent drk = new Intent(Main.this, ProjektDRK.class);
                 startActivity(drk);

             case 9:
                 Intent give = new Intent(Main.this, ProjektGIVE.class);
                 startActivity(give);

             case 10:
                 Intent hive = new Intent(Main.this, ProjektHIV.class);
                 startActivity(hive);

             case 11:
                 Intent jo = new Intent(Main.this, ProjektJOHANNITER.class);
                 startActivity(jo);

             case 12:
                 Intent kind = new Intent(Main.this, ProjektKINDERHERZ.class);
                 startActivity(kind);

             case 13:
                 Intent kult = new Intent(Main.this, ProjektKULTURGUT.class);
                 startActivity(kult);
             }
        }
       };

и здесь метод рандомизатора:

 public void imageRandomizer(String imgName, int id, final Button imgView) {
    id = getResources().getIdentifier(imgName, "drawable", getPackageName());  
    imgView.setBackgroundResource(id);
    imgView.setTag(new Integer(1)); //example for image 1
    if (imgName.equals("img1")) {
        imgView.setTag(new Integer(1)); //example for image 1
     } else if (imgName.equals("img2")) {
        imgView.setTag(new Integer(2));
     } else if (imgName.equals("img3")) {
         imgView.setTag(new Integer(3));
     } else if (imgName.equals("img4")) {
         imgView.setTag(new Integer(4));
     } else if (imgName.equals("img5")) {
         imgView.setTag(new Integer(5));
     } else if (imgName.equals("img6")) {
         imgView.setTag(new Integer(6));
     } else if (imgName.equals("img7")) {
         imgView.setTag(new Integer(7));
     } else if (imgName.equals("img8")) {
         imgView.setTag(new Integer(8));
     } else if (imgName.equals("img9")) {
         imgView.setTag(new Integer(9));
     } else if (imgName.equals("img10")) {
         imgView.setTag(new Integer(10));
     } else if (imgName.equals("img11")) {
         imgView.setTag(new Integer(11));
     } else if (imgName.equals("img12")) {
         imgView.setTag(new Integer(12));
     }
    else if (imgName.equals("img13")) {
        imgView.setTag(new Integer(13));
    }
}
  • 1
    Вам не хватает оператора break в вашей конструкции switch / case.
  • 0
    Большое спасибо за напоминание. Виноват
Теги:
imagebutton

1 ответ

1
Лучший ответ

Я бы использовал тег для идентификации кнопки. Поэтому в вашем imateRandomizer добавьте уникальный идентификатор для каждого возможного изображения. Я не знаю, как вы можете однозначно идентифицировать изображения, но я покажу здесь пример для имени:

public void imageRandomizer(String imgName, int id, final Button imgView)
    {
        id = getResources().getIdentifier(imgName, "drawable", getPackageName());  
        imgView.setBackgroundResource(id);

        if (imgName.equals("Name of the Image for your first activity") {
           imgView.setTag(new Integer(1)); //example for image 1
        } else if (imgName.equals("Name of the Image for your second activity") {
           imgView.setTag(new Integer(2));
        }
    }

И затем в вашем ClickListener вы можете проверить, какой тег имеет кнопка:

imgView.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 switch((Integer) v.getTag()) {

                      case 1: //start Activity 1;

                      break;

                      case 2: //start Activity 2;

                      break;
                 }
             }
         });
  • 0
    это не помогает, только случай 13, который читается. 13 - общая сумма коллекции случайных изображений
  • 0
    Можете ли вы показать, как вы устанавливаете и читаете теги?
Показать ещё 9 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню