国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

android - 如何通過加減按鈕實現動態EditText?

瀏覽:163日期:2024-08-31 17:59:01

問題描述

我想通過兩個按鈕來實現這種效果。 App運行的時候,屏幕只出現一個EditText。 然后點加號按鈕,下面就出現一個新的EditText(帶有減號在旁邊)。 點擊減號就刪除。

android - 如何通過加減按鈕實現動態EditText?

還有一個問題就是這種效果是不是通過Listview實現?

跪求大神們的高見和指點!

問題解答

回答1:

如果需要滑動就用RecyclerView,點擊新增的時候往adapter里面插入數據然后更新更新視圖

如果數量不會很多,直接用LinearLayout,然后點擊時動態添加子View,然后重繪LinearLayout就行了

這種效果有2個主要部件, 第一個是外層的容器(后面叫父視圖)用來放置具體的子視圖, 可以用一個豎直的LinearLayout. 第二個就是你要動態添加的子視圖, 這個子視圖應該包含一個EditText和一個Button. 我假設你知道怎樣創建子視圖了

操作就是點擊新增的按鈕就在父視圖中使用ViewGroup.addView()方法增加一個子視圖, 也就是你說的'EditText', 然后如果父視圖的大小沒有發生變化的話, 就調用父視圖的invalidate()方法重繪父視圖, 那么你剛才add進去的子視圖就會顯示出來了, 也就新增成功了. 如果父視圖的大小發生了變化, 就調用requestLayout(). 刪除操作一樣, 就是點擊刪除按鈕的時候就用ViewGroup.removeView()刪除對應的子視圖, 然后再invalidate()/requestLayout()

activity的布局

<?xml version='1.0' encoding='utf-8'?><LinearLayout xmlns:android='http://schemas.android.com/apk/res/android' android: android:layout_width='match_parent' android:layout_height='match_parent' android:orientation='vertical' > <include layout='@layout/edt'/></LinearLayout>

R.layout.edt文件, 子控件的布局

<?xml version='1.0' encoding='utf-8'?><LinearLayout xmlns:android='http://schemas.android.com/apk/res/android' android:layout_width='match_parent' android:layout_height='wrap_content' android:orientation='horizontal'> <EditTextandroid:layout_width='0dp'android:layout_height='44dp'android:layout_weight='1'/> <Buttonandroid: android:layout_width='44dp'android:layout_height='44dp' /></LinearLayout>

activity的關鍵代碼

@Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.btn).setOnClickListener(this); }@Override public void onClick(View view) {// 父控件final LinearLayout container = (LinearLayout) findViewById(R.id.main);// 根據tag區分是新增view還是刪除viewString tag = (String) view.getTag();if ('-'.equals(tag)) { // 刪除view // 獲取子控件 View child = (View) view.getParent(); // 從父控件中移除子控件 container.removeView(child);} else { // 新增view // 創建子控件實例 View child = LayoutInflater.from(MainActivity.this).inflate(R.layout.edt, container, false); // 獲取其中的button View btn = child.findViewById(R.id.btn); // 監聽點擊事件 btn.setOnClickListener(this); // 設置刪除的tag btn.setTag('-'); // 添加進父控件 container.addView(child);}// 請求重繪container.invalidate(); }

關鍵代碼如上

container就是上面說的父控件, 是一個LinearLayout

R.layout.edt就是上面說的子控件的布局, 其中的按鈕就是R.id.btn

相關文章:
主站蜘蛛池模板: 象州县| 汶川县| 海盐县| 宣武区| 余干县| 翁牛特旗| 西乌珠穆沁旗| 广灵县| 界首市| 罗甸县| 贡觉县| 萨迦县| 博罗县| 青神县| 尤溪县| 潜江市| 通州市| 湛江市| 平原县| 河北省| 云龙县| 鄱阳县| 长沙市| 宁强县| 吉木乃县| 衡南县| 新津县| 德昌县| 上思县| 商南县| 嘉祥县| 高安市| 都安| 镇坪县| 重庆市| 博爱县| 义乌市| 湖口县| 普定县| 璧山县| 威宁|