动画 --- 添加 和 移除 按钮

 1 import android.app.Activity;
 2 import android.os.Bundle;
 3 import android.view.Menu;
 4 import android.view.MenuItem;
 5 import android.view.View;
 6 import android.view.View.OnClickListener;
 7 import android.widget.Button;
 8 import android.widget.LinearLayout;
 9 
10 public class MainActivity extends Activity {
11 
12     private LinearLayout rootView;
13 
14     @Override
15     protected void onCreate(Bundle savedInstanceState) {
16         super.onCreate(savedInstanceState);
17         setContentView(R.layout.fragment_main);
18 
19         rootView = (LinearLayout) findViewById(R.id.rootView);
20     }
21 
22     // 添加按钮
23     private void addButton() {
24         Button btn = new Button(this);
25         btn.setText("Remove me");
26         rootView.addView(btn);
27         // rootView.setLayoutTransition(transition);
28         btn.setOnClickListener(btn_onclicklistener);
29     }
30 
31     // 删除按钮
32     private OnClickListener btn_onclicklistener = new OnClickListener() {
33         @Override
34         public void onClick(View arg0) {
35             rootView.removeView(arg0);
36         }
37     };
38 
39     @Override
40     public boolean onCreateOptionsMenu(Menu menu) {
41         getMenuInflater().inflate(R.menu.main, menu);
42         return true;
43     }
44 
45     @Override
46     public boolean onOptionsItemSelected(MenuItem item) {
47         switch (item.getItemId()) {
48         case R.id.action_add:  
49             addButton();
50             break;
51         }
52         return super.onOptionsItemSelected(item);
53     }
54 
55 }

 

 

R.layout.fragment_main

<LinearLayout 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:orientation="vertical"
    android:id="@+id/rootView"
    android:animateLayoutChanges="true"
    tools:context="com.l02layoutchangeanim.MainActivity$PlaceholderFragment" >
</LinearLayout>

 

R.menu.main

1 <menu xmlns:android="http://schemas.android.com/apk/res/android"
2     xmlns:tools="http://schemas.android.com/tools"
3     tools:context="com.l02layoutchangeanim.MainActivity" >
4     <item
5         android:id="@+id/action_add"
6         android:showAsAction="always"
7         android:icon="@android:drawable/ic_input_add"/>
8 </menu>

 

 

 

posted on 2014-08-31 19:56  大米稀饭  阅读(317)  评论(0编辑  收藏  举报