从普通的类方法开始新活动

时间:2014-12-01 19:45:32

标签: java android android-activity

我不知道如何在一个可以启动另一个活动的类中编写方法。

我有一个带有5个按钮的页脚,每个按钮都应该启动一个新活动。我想用5个开始活动的方法创建一个类。

我想做那样的事情:

我的Footer_buttons课程:

public class Footer_buttons{

//Back to Home activity
    public static void home_footer(Context context) {   

        Intent intent = new Intent(context, Home_page.class);
        context.startActivity(intent);
    }
}

在我的一项活动中,我想称之为:

    private static Context context;
....
        context = this;
....

    public void home_footer(View view) {    
        Footer_buttons.home_footer(context);
    }

1 个答案:

答案 0 :(得分:2)

您可以通过几种不同的方式指定按钮应执行的行为。

xml onClick属性 首先,按钮具有名为onClick的xml属性。您可以为此属性指定方法名称:

<Button
    android:id="@+id/btnMyButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/lbl_click_here"
    android:onClick="goToActivity" />

此按钮将调用此布局所属的Activity中的goToActivity方法。

public void goToActivity(View view) {
 Intent i = new Intent(this,NewActivity.class);
 startActivity(i);

}

片段中的onClickListener 以下示例在片段的onCreateView事件期间将onClickListener应用于片段布局中的按钮。

这是片段xml中的按钮:

<Button
    android:id="@+id/btnMyButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/lbl_click_here" />

请注意,我们不再使用按钮的onClick xml属性。

onClickListener是一个接口,可以在fragment类中实现为匿名类:

View rootView = inflater.inflate(R.layout.fragment_main, container, false);

// Find your button in the layout.
Button btnMyButton = (Button) rootView.findViewById(R.id.btnMyButton);

btnMyButton.setOnClickListener(new OnClickListener() {

  @Override
  public void onClick(View v) {
        Intent i = newIntent(getActivity(),NewActivity.class);
        startActivity(i);
  }

});

活动中的onClickListener 以下示例在片段的onCreate事件期间将onClickListener应用于Activity的布局中的按钮。

这是片段xml中的按钮:

<Button
    android:id="@+id/btnMyButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/lbl_click_here" />

再一次,我们不使用按钮的onClick xml属性。

onClickListener接口现在作为活动类内的匿名类实现:

    // Find your button in the layout.
Button btnMyButton = (Button)findViewById(R.id.btnMyButton);

btnMyButton.setOnClickListener(new OnClickListener() {

  @Override
  public void onClick(View v) {
        Intent i = newIntent(this,NewActivity.class);
        startActivity(i);
  }

});

在运行时查找xml元素

在运行时查找xml元素,如前两个示例所示,要求为元素分配一个id:

android:id="@+id/btnMyButton"

并且在调用代码中引用了此ID:

R.id.btnMyButton

当一个活动在其布局中寻找元素时,它可以直接调用findByView方法,如下所示:

Button btnMyButton = (Button)findViewById(R.id.btnMyButton);

当片段在其布局中查找元素时,它必须首先在其自己的视图上调用findViewByID,如下所示:

Button btnMyButton = (Button) rootView.findViewById(R.id.btnMyButton);

<强>铸造

请注意,在这两个示例中,findViewByID的返回值都被强制转换为声明的类型 - 在本例中为Button。

Button btnMyButton = (Button)...

findViewByID默认返回一个View - View是Button的父级,代表最常规的类型。

相关问题