簡體   English   中英

ImageButton的圖像未按預期更改

[英]Image for ImageButton doesn't change as intended

我的目標是從ImageButton(ibChamp)更改圖像。

package com.example.custombuilds;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;z
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class Champions extends Activity {

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

    ImageButton ibAnnie = (ImageButton) findViewById(R.id.ibAnnie);

    ibAnnie.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Check this for errors
            RelativeLayout test = (RelativeLayout) findViewById(R.id.layoutChampions);
            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = layoutInflater.inflate(R.layout.create_build_page, null);
            test.addView(view);
            ImageButton img = (ImageButton) view.findViewById(R.id.ibChamp);
            img.setImageResource(R.drawable.ic_launcher);

            try {
                Intent open = new Intent("android.intent.action.CREATE");
                startActivity(open);
            } catch (Exception e) {

            }

        }
    });
}
}

請注意,ImageButton ibChamp來自xml布局create_build_page,而不是來自xml冠軍。 這段代碼運行時沒有崩潰,但是Imagebutton ibChamp中的Image並沒有改變,這就是我想要做的。 我很樂意提供其他任何信息。

您正在onClick中誇大“ ibChamp”。 這將創建一個新的ImageButton。 在使用父級的“ addView”之前,您將看不到它。

您可以添加XML,但是您需要獲得對Activity中現有按鈕的引用才能對其進行更改。 否則,添加新按鈕並刪除舊按鈕...

換句話說,更改此:

        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.create_build_page, null);
        ImageButton img = (ImageButton) view.findViewById(R.id.ibChamp);

對此:

        ImageButton img = (ImageButton)findViewById(R.id.ibChamp);

它可能會做您想要的。

您需要為此膨脹視圖調用addView()

View view = layoutInflater.inflate(R.layout.create_build_page, null);

暫無
暫無

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

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