2010-07-01 67 views
0
package com.iperetz1.android.testbutton1; 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 

public class TestButton extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Button test2 = (Button)findViewById(R.id.test2);  
     test2.setOnClickListener(new OnClickListener() 
     { 
      @Override 
      public void onClick(View v) 
      { 
       setContentView(R.layout.test2);; 
      } 
     }); 

     Button other = (Button)findViewById(R.id.backmain);  
     other.setOnClickListener(new OnClickListener() 
     { 
      @Override 
      public void onClick(View v) 
      { 
       setContentView(R.layout.main);; 
      } 
     }); 
    } 
} 

main.xls错误“的Android(项目名称)已意外停止

<?xml version="1.0" encoding="utf-8"?> 
<AbsoluteLayout 
android:id="@+id/widget0" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
xmlns:android="http://schemas.android.com/apk/res/android" 
> 
<Button 
android:id="@+id/test2" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="test2" 
android:layout_x="24px" 
android:layout_y="165px" 
> 
</Button> 
</AbsoluteLayout> 

test2.xml

<?xml version="1.0" encoding="utf-8"?> 
<AbsoluteLayout 
android:id="@+id/widget0" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
xmlns:android="http://schemas.android.com/apk/res/android" 
> 
<Button 
android:id="@+id/backmain" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="backmain" 
android:layout_x="24px" 
android:layout_y="165px" 
> 
</Button> 
</AbsoluteLayout> 
+0

这很简单,因为您不能这么做(更改内容视图) – Cristian 2010-07-01 19:54:29

+0

可以吗发给我我在哪里可以找到如何做到这一点的权利 – iperetz1 2010-07-01 20:01:14

+0

使用logcat通常会帮助排查这些类型的错误。 http://developer.android.com/guide/developing/tools/adb.html – 2010-07-01 20:16:45

回答

0

正如@Cristian Castiblanco说,动态改变视图导致问题,对于这些场景,您必须创建单独的活动并使用意向调用它们,并使用捆绑包在它们之间传递数据。

+0

你可以帮助修复代码,这对我来说是一个很大的帮助 – iperetz1 2010-07-03 02:54:40

1

findViewById比人们倾向于认为它简单得多。它遍历视图层次结构,查找具有给定ID的视图。如果没有找到,findViewById返回null。

您首先将内容视图设置为main布局,但后来尝试findViewById(R.id.backmain)。由于在主布局中没有该ID,所以它返回null。那时尝试other.setOnClickListener将失败。只有当按钮实际存在于视图层次结构中时,才能执行此操作。

动态更改视图层次结构并没有什么内在错误,但是如果你走这条路线,你将不得不处理一些不同的事情。 (例如,当您将事件连接到onCreate期间不存在的视图时,就像上面要做的那样)。