zoukankan      html  css  js  c++  java
  • Android获取页面元素

    1.布局文件layout/activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="我是一个TextView"/>
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按钮"/>
    
        <EditText
            android:id="@+id/editText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="输入点什么吧..."/>
    
    </LinearLayout>

    2.页面处理MainActivity.java

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            LinearLayout linearLayout=(LinearLayout) this.getLayoutInflater().inflate(R.layout.activity_main,null);
            setContentView(linearLayout);
    
            int childCount=linearLayout.getChildCount();
            for (int i=0;i<childCount;i++){
                View childView=linearLayout.getChildAt(i);
                childView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(v instanceof Button){
                            Toast.makeText(MainActivity.this,"我点击的是一个Button!",Toast.LENGTH_SHORT).show();
                        }else if(v instanceof EditText){
                            Toast.makeText(MainActivity.this,"我点击的是一个EditText!",Toast.LENGTH_SHORT).show();
                        }else if(v instanceof TextView){
                            Toast.makeText(MainActivity.this,"我点击的是一个TextView!",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }
    }

    3.知识点总结:

    • inflate方法可用获取view对象,实现动态页面加载
    • getChildCount()和getChildAt()可用用于获取子元素个数和元素示例
    • instanceof 运算符用来判断对象是否是特定类的一个实例
    • 任何元素都可以添加点击事件
  • 相关阅读:
    诚聘Python等课程兼职讲师
    Ogre3d
    OGRE中 场景管理器,场景节点和实体
    第四天:原型模式建造者模式
    第二天:装饰模式及面向对象设计原则4则
    表达式求值:面向对象版本
    第五天:模板方法外观模式观察者模式
    第三天:代理模式工厂方法抽象工厂
    第一天:简单工厂与策略模式
    idea files count
  • 原文地址:https://www.cnblogs.com/ltw222/p/14911965.html
Copyright © 2011-2022 走看看