ImageButton更改另一个ImageButton的图像会导致意外的周期

时间:2014-02-06 21:54:58

标签: java android xml imagebutton

此后果:Image for ImageButton doesn't change as intended

单击“ibChamp”的ImageButton时,会打开champions.xml。在该布局中,有一个名为“ibAnnie”的Imagebutton。单击时我想要做的是,更改“ibChamp”的图像,并切换到该布局。这里发生的是在点击“ibAnnie”之后,它切换到“create_build_page.xml”,并且在那里是“ibChamp”的改变图片。但是这只会在返回到原始的,未更改的图片“create_build_page.xml”布局之前一瞬间发生。当我单击后退按钮时,它会转到带有更改图片的“create_build_page.xml”布局,但按钮不起作用。我很乐意提供所需的任何其他信息。

1 个答案:

答案 0 :(得分:0)

我仍然不完全清楚你想要实现的目标......但如果我的理解是正确的,那么这会让你更接近:

@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) {
            RelativeLayout test = (RelativeLayout) findViewById(R.id.layoutChampions);
            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View createView = layoutInflater.inflate(R.layout.create_build_page, null);
            test.addView(createView);

            ImageButton img = (ImageButton) view.findViewById(R.id.ibChamp);
            img.setImageResource(R.drawable.ic_launcher);
            img.setTag(R.drawable.ic_launcher); // so you can retrieve it later
            img.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    // this will set the imageView of ibAnnie
                    ibAnnie.setImageView((Integer)view.getTag());
                    // this will remove the selection view from your layout
                    ((RelativeLayout) findViewById(R.id.layoutChampions)).removeChild(createView);
                }
            });

            // this opens another Activity... you don't want that, at least not for what you seem to be trying to do.
            /*try {
                Intent open = new Intent("android.intent.action.CREATE");
                startActivity(open);
            } catch (Exception e) {

            }*/

        }
    });
}