Search code examples
androidimagebutton

starting a new layout on clicking image button


I have following code that should open a new layout(.xml file) on clicking an ImageButton.

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageButton img = (ImageButton) findViewById(R.id.imageView1);
    img.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.board_play);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

But I get an error in onClick method. Help what could I change to remove the error. Am I using correct implementation to change the layout using an ImageButton?


Solution

  • Setting different layouts to the same activity is bad design. Every Activity has a life cycle and should have just one layout set to the activity.

    Instead start a new Activity and set board_play to the same.

    Use

      @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this,BoardActivity.class));
        }
    

    In BoardActivity

     public class BoardActivity extends Activity
     {
         @Override
         protected void onCreate(final Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.board_play);
     }
    

    Make sure you make an entry for BoarActivity in manifest file.

    You can also use fragments.