ImageButton的图像不会按预期更改

时间:2014-02-06 01:05:46

标签: java android imagebutton

我的目标是从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不会改变,这正是我想要做的。我很乐意提供任何其他信息。

2 个答案:

答案 0 :(得分:0)

你在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);

它可能会做你想要的。

答案 1 :(得分:0)

你需要为这个膨胀的视图调用addView()

View view = layoutInflater.inflate(R.layout.create_build_page, null);
相关问题