簡體   English   中英

將動態字符串傳遞給活動

[英]Passing dynamic string to activity

我在循環中創建了一個帶有動態按鈕的活動。 我得到一個列表並為列表中的每個元素創建一個按鈕。 之后按鈕會轉到相同的活動,但是每個按鈕我想要傳遞不同的字符串。

我在循環中做了這個:

    tour_button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(TourListActivity.this,
                    TourMenuActivity.class);
            String info = tour.toString();
            intent.putExtra(TOUR_INFO, info);
            startActivity(intent);
        }
    }); 

但最后,所有按鈕都獲得相同的字符串(最后一個按鈕的字符串)。

========================================完整代碼:

   try {
        JsonObject respObject = jsonParser.parse(response).getAsJsonObject();
        JsonArray tourListArray = respObject.getAsJsonArray("tours");
        System.out.println("tourListArray: " + tourListArray.toString());

        for(int i = 0; i < tourListArray.size(); i++){
            LinearLayout ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.VERTICAL);
            tour = tourListArray.get(i).getAsJsonObject();
            String tourCode = tour.get("tourcode").getAsString();
            Button tour_button = new Button(this);  
            tour_button.setText("Tour Code: " + tourCode);
            tour_button.setGravity(Gravity.LEFT);
            tour_button.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(TourListActivity.this,
                            TourMenuActivity.class);
                    String info = tour.toString();
                    intent.putExtra(TOUR_INFO, info);
                    startActivity(intent);
                }
            }); 


            ll.addView(tour_button);

            LinearLayout yourLL = (LinearLayout) findViewById(R.id.Tours_List);
            yourLL.setOrientation(LinearLayout.VERTICAL);
            yourLL.addView(ll);  


        }
    } catch (JsonIOException e) {
        e.printStackTrace();
    } 

創建按鈕時,您可以:

 button.setTag(someString); 

然后在onClick中你可以:

public void onClick(View v) {
        Intent intent = new Intent(TourListActivity.this,
                TourMenuActivity.class);
        String info = tour.toString();
        intent.putExtra(TOUR_INFO, ((Button)v).getTag());
        startActivity(intent);
    }

變量tour在循環外定義,因此每個按鈕共享相同的變量 在每次迭代中,您只需更改此變量存儲的引用

您可以在循環中創建最終變量,並在OnClickListener使用它:

for (int i = 0; i < tourListArray.size(); i++) {
    ...
    final String tourInfo = tour.info;
    tour_button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(
                TourListActivity.this, 
                TourMenuActivity.class
            );
            intent.putExtra(TOUR_INFO, tourInfo);
            startActivity(intent);
        }
    });
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM