Android · 2012/12/26

切换 Activity的View

Android应用有多个界面的时候,新手(比如我)为每个界面新建了一个activity,虽然也能实现切换,不过费cpu和ram,我说怎么切换起来屏幕有个明显的闪动呢。目前发现应该用LayoutInflater切换view比较靠谱,当然这可能也是个新手做法啦。

感谢eoeandroid论坛k850i提供的sample: http://www.eoeandroid.com/thread-101286-1-1.html,下面是我的代码(极度简化),就是viewa和viewb来回切换:

public class Main extends Activity {

    View viewa, viewb;

    

    @Override

    protected
void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        LayoutInflater flater = this.getLayoutInflater();

        viewa = flater.inflate(R.layout.activity_a, null);

        viewb = flater.inflate(R.layout.activity_b, null);    

        

        setContentView(viewa);

        ImageView IV_b = (ImageView)findViewById(R.id.IV_b);

        IV_b.setOnClickListener(new OnClickListener(){

         public
void onClick(View v){

             setContentView(viewb);

             

             ImageView IV_a = (ImageView)findViewById(R.id.IV_a);

             IV_a.setOnClickListener(new OnClickListener(){

              public
void onClick(View v){

                  setContentView(viewa);

              }

          });             

         }

     });        

    }

}