我从中学习
http://developer.android.com/reference/android/widget/Button.html
Run Code Online (Sandbox Code Playgroud)
"而不是将OnClickListener应用于活动中的按钮,您可以使用android:onClick属性为XML布局中的按钮指定方法."
但是,我只能用XML方法完成它,我的监听器方法由以下指定,导致应用程序崩溃.
在我的fragment_main.xml中:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.myapp.MainActivity$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/try_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "TryButton"
android:onClick="onClick"
/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
在我的activity_main.xml中:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myapp.MainActivity"
tools:ignore="MergeRootFrame">
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)
在我的MainActivity.java中:
public class MainActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
Button button = (Button)findViewById(R.id.try_button);
button.setOnClickListener(this);
}
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "I'm …Run Code Online (Sandbox Code Playgroud)