zoukankan      html  css  js  c++  java
  • 2021.5.17 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 运算符用来判断对象是否是特定类的一个实例
    • 任何元素都可以添加点击事件


    作者:艾满
    链接:https://www.jianshu.com/p/9839558332b3

  • 相关阅读:
    sql server 2016新特性 查询存储(Query Store)的性能影响
    Spring 事务管理详情介绍
    python爬虫之快速对js内容进行破解
    python爬虫的一个常见简单js反爬
    温习pycharm
    宋朝官员分析随堂理解笔记
    K-Means改进模式
    jupyter 饼图
    WebDriver常用的API使用详解
    从浏览器启动开始
  • 原文地址:https://www.cnblogs.com/wmdww/p/14907266.html
Copyright © 2011-2022 走看看