摘要:
本节主要涉及到的有activity的创建,标题栏隐藏,button绑定方法(toast的使用),menu使用,活动销毁
1.activity的创建跟注册
创建:
public class TestActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
注册:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".TestActivity"
android:label="TestActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter>
</activity>
</application>
2.隐藏标题栏
在TestActivity中的onCreate中调用接口就行
public class TestActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
}
}
3.给button绑定方法(toast为例)
(1)创建button
在activity_main.xml(layout处)中新增button
<Button
android:id="@+id/button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="alex"
/>
(2)通过id来绑定方法
public class TestActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
final Button button_test = (Button) findViewById(R.id.button_1);
button_test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(TestActivity.this,"You Click Test Button",Toast.LENGTH_SHORT).show();
}
});
}
}
3.menu使用
(1).增加menu
默认对应的menu在res/menu中,在这里是menu_main.xml,在这里增加两个选择
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/add_item"
android:title="Add"/>
<item
android:id="@+id/remove_item"
android:title="Remove"/>
</menu>
(2)重写onCreateOptionsMenu ,允许菜单栏显示出来
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
(3)增加菜单栏的响应事件
@Override
public boolean onOptionsItemSelected(MenuItem menu) {
switch (menu.getItemId()) {
case R.id.add_item:
Toast.makeText(this, "You clicked Add", Toast.LENGTH_SHORT).show();
break;
case R.id.remove_item:
Toast.makeText(this, "You clicked Remove", Toast.LENGTH_SHORT).show();
break;
default:
}
return true;
}
4.活动销毁
销毁活动比较简单,绑定某个操作就行了。
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
} });