Android:在一个活动中意图启动另一个活动

时间:2012-10-02 10:17:28

标签: android button android-intent

很抱歉,我对android开发很新,现在我想锻炼当用户按下按钮时,它会启动Actitity2,同样当用户按下Activity2中的取消按钮时,它将返回到最初的活动。

我参考了有关编写应用程序的书,但似乎无法正常工作,编码看起来很简单,如下所示:

public class NameIndex extends Activity 
{
       // called when the activity is first created
       @Override
       public void onCreate(Bundle savedInstanceState) 
       {
          super.onCreate(savedInstanceState); 
          setContentView(R.layout.name_index);

           public button_cancel_click (View view) { /////// <-- ERROR AT THIS LINE
               Intent intent = new Intent (this, GameIndex.class);
               startActivity(intent);
           }
       } // end method onCreate
}

xml布局如下:

    <TableRow android:id="@+id/tableRow1" 
      android:layout_height="match_parent" 
      android:layout_width="match_parent"
      android:paddingBottom="10dp"
      android:paddingTop="10dp"      
      android:layout_span="2" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_span="1"
            android:layout_weight="1"
            android:onClick="button_cancel_click"            
            android:text="Cancel" />     
    </TableRow>          

Eclipse将上述错误行报告为“ button_cancel_click无法解析为类型”,以及

查看“参数视图的非法修饰符;仅允许最终”。

怎么能解决这个问题?

2 个答案:

答案 0 :(得分:4)

你正在OnCreate函数体中编写button_cancel_click函数的定义,如下所示:

public void onCreate(Bundle savedInstanceState)
{
.
.
.
}
public button_cancel_click (View view) 
{
.
.
}

答案 1 :(得分:0)

应该以这种方式添加监听器:

super.onCreate(savedInstanceState); 
setContentView(R.layout.name_index);
Button button = (Button ) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {                       
                    public void onClick(View v) {
                        Intent intent = new Intent (this, GameIndex.class);
           startActivity(intent);
                    }
                });