【Android】基础—常用控件、Intent

功能组件

按钮

在layout里进行配置

<LinearLayout
    android:layout_width="match_parent"     <!-- 设置LinearLayout的宽度与父容器相同,填满可用空间 -->
    android:layout_height="match_parent">   <!-- 设置LinearLayout的高度与父容器相同,填满可用空间 -->

    <Button
        android:id="@+id/button_1"         <!-- 指定按钮的唯一标识符为button_1,可以在代码中引用 -->
        android:layout_width="match_parent" <!-- 设置按钮的宽度与其父布局(LinearLayout)相同,填满可用空间 -->
        android:layout_height="wrap_content"<!-- 设置按钮的高度根据其内容自适应,包裹内容 -->
        android:text="Button 1">            <!-- 按钮显示的文本内容为 "Button 1" -->

    </Button>                               <!-- 结束按钮的定义 -->

</LinearLayout>                             <!-- 结束LinearLayout的定义 -->

通知小信息(弹出后消失)

在创建的Activity里进行重写

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // 调用父类的 onCreate 方法,执行默认的初始化操作
    setContentView(R.layout.first_layout); // 设置当前 Activity 的布局文件为 first_layout.xml

    // 通过 findViewById 找到布局文件中定义的按钮,并将其赋给 button1 变量
    Button button1 = (Button) findViewById(R.id.button_1);

    // 设置按钮的点击事件监听器
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // 当按钮被点击时执行的操作
            Toast.makeText(FirstActivity.this, "别点了,再点我直接爆炸", Toast.LENGTH_SHORT).show();
            // 弹出一个短暂的提示信息,显示 "别点了,再点我直接爆炸"
        }
    });
}

菜单

在res里添加menu,在menu中进行内容编写

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/add_item"      <!-- 菜单项的唯一标识符,可以在代码中引用 -->
        android:title="Add"/>           <!-- 菜单项显示的标题为 "Add" -->

    <item
        android:id="@+id/remove_item"   <!-- 菜单项的唯一标识符,可以在代码中引用 -->
        android:title="Remove"/>        <!-- 菜单项显示的标题为 "Remove" -->

</menu>

在创建的Activity中先重写onCreateOptionsMenu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // 加载菜单布局文件到当前的选项菜单中
    getMenuInflater().inflate(R.menu.main, menu);
    return true; // 返回 true 表示菜单已经成功创建并显示在 Activity 上
}

显示菜单后我们还需要给菜单添加响应时间(这里用上文的Toast举例)

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // 当用户点击某个选项菜单项时调用此方法,并传入被点击的 MenuItem 对象 item

    // 判断被点击的菜单项的唯一标识符(ID)是否等于 R.id.add_item
    if (item.getItemId() == R.id.add_item) {
        // 如果是 add_item 被点击了,则显示一个短暂的提示信息“你选了Add”
        Toast.makeText(this, "你选了Add", Toast.LENGTH_SHORT).show();
    } 
    // 判断被点击的菜单项的唯一标识符(ID)是否等于 R.id.remove_item
    else if (item.getItemId() == R.id.remove_item) {
        // 如果是 remove_item 被点击了,则显示一个短暂的提示信息“你选了Remove”
        Toast.makeText(this, "你选了Remove", Toast.LENGTH_SHORT).show();
    }

    return true; // 返回 true 表示事件已经处理完成
}

Intent

显式Intent

// 创建一个 Intent 对象,用于启动 SecondActivity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);

// 使用该 Intent 启动 SecondActivity
startActivity(intent);

隐式Intent

<activity
    android:name=".SecondActivity"
    android:exported="true" >

    <!-- 设置 SecondActivity 的 intent-filter -->
    <intent-filter>
        <action android:name="com.example.activitytest.ACTION_START" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

            
Intent intent = new Intent("com.example.activitytest.ACTION_START");
startActivity(intent);           

每个Intent只能对应一个action,但是可以指定多个category。

可以再添加一个category:

public void onClick(View v) {
    // 创建一个新的 Intent 对象,动作为 "com.example.activitytest.ACTION_START"
    Intent intent = new Intent("com.example.activitytest.ACTION_START");
    
    // 添加自定义的类别 "com.example.activitytest.MY_CATEGORY" 到 Intent 中
    intent.addCategory("com.example.activitytest.MY_CATEGORY");
    
    // 启动指定的 Activity
    startActivity(intent);
}

同时在<intent-filter>中也要添加上(不然程序会崩溃):

<intent-filter>
    <!-- 定义 Intent 的动作 -->
    <action android:name="com.example.activitytest.ACTION_START" />
    
    <!-- 默认类别 -->
    <category android:name="android.intent.category.DEFAULT" />
    
    <!-- 自定义类别 -->
    <category android:name="com.example.activitytest.MY_CATEGORY" />
</intent-filter>

传递数据与返回数据

向下一个活动传递数据

在FirstActivity中进行传递

public void onClick(View v) {
    // 准备要传递的数据
    String data = "HeHe";
    
    // 创建 Intent 对象,指定启动 FirstActivity 到 SecondActivity
    Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
    
    // 将额外的数据放入 Intent 中,键为 "extra_data"
    intent.putExtra("extra_data", data);
    
    // 启动 SecondActivity
    startActivity(intent);
}

在SecondActivity中进行接收

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    // 启用边缘到边缘显示
    EdgeToEdge.enable(this);
    
    // 设置布局文件
    setContentView(R.layout.second_layout);
    
    // 获取传递过来的 Intent
    Intent intent = getIntent();
    
    // 从 Intent 中获取额外的数据
    String data = intent.getStringExtra("extra_data");
    
    // 将数据打印到日志中
    Log.d("SecondActivity", data);
}

向上一个活动返回数据

在FristActivity中重写:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.first_layout);

    // 获取按钮对象并设置点击事件监听器
    Button button1 = findViewById(R.id.button_1);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // 创建一个意图,启动 SecondActivity 并等待返回结果
            Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
            startActivityForResult(intent, 1);
        }
    });
}

在SecondActivity中进行点击终止并传递

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    EdgeToEdge.enable(this); // 使用 EdgeToEdge 库进行边缘到边缘的显示
    setContentView(R.layout.second_layout); // 设置布局文件

    // 获取按钮对象并设置点击事件监听器
    Button button2 = findViewById(R.id.button_2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // 创建一个新的意图
            Intent intent = new Intent();

            // 在意图中添加额外的数据,键为 "Data_return",值为 "HaHa"
            intent.putExtra("Data_return", "HaHa");

            // 设置返回结果为 RESULT_OK,并将包含数据的意图传递回上一个活动
            setResult(RESULT_OK, intent);

            // 结束当前活动,返回上一个活动
            finish();
        }
    });
}

在FirstActivity接收并打印

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // 判断返回的结果码是否为 RESULT_OK
    if (resultCode == RESULT_OK) {
        // 从意图中获取返回的额外数据,键名为 "Data_return"
        String returnedData = data.getStringExtra("Data_return");

        // 使用 Log 输出返回的数据到控制台
        Log.d("FirstActivity", returnedData);
    }
}

常用控件

TextView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/text_view"//给当前控件唯一标识符
        android:layout_width="match_parent"//宽
        android:layout_height="wrap_content"//高
        android:textSize="24sp"//字体大小
        android:textColor="#00ff00"//文本颜色
        android:text="xiaoduyyy"//文本内容
        android:gravity="center"/>//对齐方式

</LinearLayout>

Button

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/button"//唯一标识符
        android:layout_width="match_parent"//宽
        android:layout_height="wrap_content"//高
        android:text="Button"//内容
        android:textAllCaps="false"/>//是否进行大写转换

</LinearLayout>

可以在MainActivity中为Button点击事件注册一个监听器

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加内容
            }
        });
    }
}

EditText

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入您的名称"//提示信息
        android:maxLines="2"/>//限制行数
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="确定"
        android:textAllCaps="false"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity {
    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.edit_text);//获取实例
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputText = editText.getText().toString() + ",你好";//获取文本并转换为字符串
                Toast.makeText(MainActivity.this, inputText, Toast.LENGTH_SHORT).show();//打印
            }
        });
    }
}

ImageView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/img_1"/>//指定图片
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点击更换图片"/>
</LinearLayout>

实现更换图片需要子啊MainActivity中进行修改

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        imageView = (ImageView) findViewById(R.id.image_view);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageView.setImageResource(R.drawable.img_2);//更换图片
            }
        });
    }
}

ProgressBar

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal"/>//更换样式
</LinearLayout>

可以通过点击来让进度条显示或者消失

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        imageView = (ImageView) findViewById(R.id.image_view);//获取实例
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageView.setImageResource(R.drawable.img_2);
                if(progressBar.getVisibility() == View.GONE) {//判断隐藏或显示
                    progressBar.setVisibility(View.VISIBLE);
                }
                else {
                    progressBar.setVisibility(View.GONE);
                }
            }
        });
    }
}

也可以更新进度条

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        imageView = (ImageView) findViewById(R.id.image_view);
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageView.setImageResource(R.drawable.img_2);
                int progress = progressBar.getProgress();
                progressBar.setProgress(progress + 10);
            }
        });
    }
}

AlertDialog

弹出一个窗口来提示用户

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        imageView = (ImageView) findViewById(R.id.image_view);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setTitle("提示标题");
                dialog.setMessage("重要提示");
                dialog.setCancelable(false);
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {//设置确定按钮事件
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {//设置取消按钮事件
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                dialog.show();
            }
        });
    }
}

ProgressDialog

和AlertDialog类似,但是弹出的是进度条

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        imageView = (ImageView) findViewById(R.id.image_view);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setTitle("提示标题");
                progressDialog.setMessage("加载中...");
                progressDialog.setCancelable(false);//是否可以取消
                progressDialog.show();
            }
        });
    }
}

已经到底啦!!

  • 16
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值