要写几句java

package com.narumi.android_7_2;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button)findViewById(R.id.button1);
        
        btn.setOnClickListener(
        
                new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this, "你已经点了我", 2000).show();
            }
        });
    } 
}

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.narumi.android_7_2.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView1"
        android:layout_marginTop="48dp"
        android:layout_toRightOf="@id/textView1"
        android:text="点我试试" />

</RelativeLayout>

要注意的的是java里面

btn.setOnClickListener(
        
                new OnClickListener() {

这样的写法可能会报错"Cannot be resolved as a type",说不能把new OnClickListener当成参数,
“The method setOnClickListener(View.OnClickListener)in the type View is not applicable for the arguments new OnClickListener(){} ”
那是为什么呢?

是因为它没找到这个对象的父类,如果我们写成new view.OnClickListener 就不会报错,
或者,用IDE的提示框中解决方法之一:import android.view.View 来实例化改对象,
即:"import OnClickListener (android.view.View)"也可以,点完这个快速修复的链接IDE自动import到头部,看不到view.前缀也是合法的了。

此练结束,点按钮弹出toast。

posted on 2015-07-21 18:25  meeming  阅读(121)  评论(0编辑  收藏  举报



Fork me on GitHub