Android中Button控件應(yīng)該算作是比較簡(jiǎn)單的控件,然而,它的使用頻率卻是非常的高,今天,我在這里總結(jié)了三種常用的點(diǎn)擊Button實(shí)現(xiàn)其功能的方法。
1.很多時(shí)候,我們?cè)谟玫紹utton控件時(shí),往往都是“一次性”使用,這時(shí),為了方便起見(jiàn),我們一般采用的是匿名內(nèi)部類的方法,形如這樣:
2.當(dāng)Button有多個(gè)或者Button的使用次數(shù)很多時(shí),我們需要采用綁定監(jiān)聽(tīng)器的做法,其實(shí),綁定監(jiān)聽(tīng)器也有幾種方法,不過(guò),我在這里就不一一列舉了,畢竟那些方法在實(shí)際的應(yīng)用中也不常見(jiàn)。
我們一般的方法是實(shí)現(xiàn)OnClickListener接口,并實(shí)現(xiàn)其中的方法,正如這樣:
default:
break;
}
}
3.這是一種最為簡(jiǎn)單的方法,我們需要做的就是添加一個(gè)方法并為Button添加一個(gè)屬性:
那么,我們需要在代碼中添加我們?cè)趯傩灾新暶鞯姆椒ǎ?BR>
1.布局文件
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1 測(cè)試"
/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2 測(cè)試"
/>
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button3 測(cè)試"
android:onClick="clickHandler"
/>
</LinearLayout>
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button button1 = null;
private Button button2 = null;
public void findButton() {
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findButton();
button2.setOnClickListener(this);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("您點(diǎn)擊了Button1");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button2:
System.out.println("您點(diǎn)擊了Button2");
break;
default:
break;
}
}
public void clickHandler(View view) {
System.out.println("您點(diǎn)擊了Button3");
}
}
新聞熱點(diǎn)
疑難解答
圖片精選