參考博客:http://blog.csdn.net/vqqyuan/article/details/44648683#
<span style="font-size:18px;"><span style="font-family:SimSun;">public class ButtonViewSampleActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_view_samples);
LinearLayout viewContainer = (LinearLayout) findViewById(R.id.view_container);
Button button = new Button(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
button.setLayoutParams(params);
button.setBackgroundResource(R.drawable.button_selector);
viewContainer.addView(button);
}
}</span></span>
drawable.button_seletor定義在xml文件中
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/button_red" />
<item android:state_pressed="false" android:drawable="@drawable/button_green" />
</selector></span>