一、创建第一个Empty Activity

一般由三个文件对应

  • Java文件中本类
  • Layout目录中的xml
  • AndroidManifest.xml中注册

创建Java类

 与之对应一个layout的xml文件

 

 我们创建一个button,其中有两个元素

  • match_parent:指定当前元素和父元素一样宽高
  • wrap_content:适应组件中的内容的大小来动态改变宽高

 

<?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 1"/>

</LinearLayout>

然后我们回到与之对应的Java类

项目中的任何资源都会在R文件中自动生成一个id,我们只需要调用即可

package com.example.androidapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //这里生成了这行代码,没有就自己创建
        setContentView(R.layout.first_layoout);
    }
}

 我们进入AndroidManidfest.xml注册,并为之配置一个主活动,告诉程序开机就启动这个活动

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AndroidApplication"
        tools:targetApi="31" >
        <activity android:name=".FirstActivity"
            android:exported="true"
            android:label="这是第一个活动">
            <!--为程序配置主活动-->
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

启动


二、组件

Toast

起到提示的作用,这里我们让按钮被点击时提示

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //这里生成了这行代码,没有就自己创建
        setContentView(R.layout.first_layoout);
        //为按钮绑定一个Toast
        Button button1 = (Button) findViewById(R.id.Button_1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(FirstActivity.this,"按钮被按了...",Toast.LENGTH_LONG).show();
            }
        });
    }


Menu

菜单组件

我们在res目录中创建menu目录和main.xml文件

<?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="添加组件"/>
    <item android:id="@+id/remove_item"
        android:title="删除组件"/>
</menu>

 我们接着回到之前的Java类中写入点击逻辑

    public boolean OnCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }
    
    public boolean OnOptionsItemSelected(MenuItem menuItem){
        switch (menuItem.getItemId()){
            case R.id.add_item:
                Toast.makeText(this,"添加组件",Toast.LENGTH_SHORT).show();
                break;
            case R.id.remove_item:
                Toast.makeText(this,"删除",Toast.LENGTH_SHORT).show();
                break;
            default:
        }
        return true;
    }


 Intent意图

显式跳转

使用主活动跳转至其他活动

我们创建一个次活动

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".InferiorActivity">
    <Button
        android:id="@+id/Button_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 2"/>
</LinearLayout>

注册xml文件

        <!-- 为程序配置此次活动 -->
        <activity
            android:name=".InferiorActivity"
            android:label="跳转至了次活动"/>

 在java类中书写逻辑,点击按钮跳转至次活动

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layoout);
        Button button1 = (Button) findViewById(R.id.Button_1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(FirstActivity.this,InferiorActivity.class);
                startActivity(intent);
            }
        });
    }

 

 

隐式跳转

我们将上面的显示跳转修改为隐式跳转

我们就直接在注册时添加

        <activity
            android:name=".InferiorActivity"
            android:label="跳转至了次活动"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.androidapplication.jump"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layoout);
        Button button1 = (Button) findViewById(R.id.Button_1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("com.example.androidapplication.jump");
                startActivity(intent);
            }
        });
    }

 正常运行

 

传递信息

我们在主活动中创建一个字符串数据,然后将其传入次活动中

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layoout);
        Button button1 = (Button) findViewById(R.id.Button_1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String data = "我是来自主活动的数据";
                Intent intent = new Intent(FirstActivity.this,InferiorActivity.class);
                intent.putExtra("extra_data",data);
                startActivity(intent);
            }
        });
    }
public class InferiorActivity extends AppCompatActivity {

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

        Intent intent = getIntent();
        String data = intent.getStringExtra("extra_data");
        Log.d("InferiorActivity",data);
    }
}

 我们点击了按钮之后就看到了传来的数据


三、UI控件

TextView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="17sp"
        android:textColor="#00ff00"
        android:text="我们是一行文字"/>
    
</LinearLayout>

 Button

    <Button
        android:id="@+id/Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="我是一个按钮Button"
        android:textAllCaps="false"/>
<!--    textAllCaps是自动将小写转为大写,false关闭 -->

 这里使用另外两种方式,之前实现OnClickList接口的方法,之前是匿名内部类的形式实现的

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.Button);
        
//        方式二
        button.setOnClickListener(this);
        
//        方式三   
        //butonholder bh = new butonholder();
        //button.setOnClickListener(bh);
    }

    //方式二
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.Button:
                //此处写逻辑
                break;
            default:
                break;
        }
    }
    
    //方式三
    class butonholder implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.Button:
                    //此处写逻辑
                    break;
                default:
                    break;
            }
        }
    }
}

EditView

输入框

与上方的按钮交互,点击按钮输出打印的内容

    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入内容"/>
    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(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.Button:
                //此处写逻辑
                String inputText = editText.getText().toString();
                Toast.makeText(MainActivity.this,inputText,Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

ImageView 

图片

    <ImageView
        android:id="@+id/image_goku"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/dargonball"/>
    private ImageView imageView;
    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);
        imageView = findViewById(R.id.image_goku);

        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.Button:
                imageView.setImageResource(R.drawable.beauty);
                break;
            default:
                break;
        }
    }

Diolog

确认对话框

直接使用,不需要再xml里   配置布局

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.Button:
                AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setTitle("提示");
                dialog.setMessage("你点击了按钮,确实更改图片吗");
                dialog.setCancelable(false);
                dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        imageView.setImageResource(R.drawable.beauty);
                    }
                });
                dialog.show();

                break;
            default:
                break;
        }
    }


四、布局

android:orientation="vertical"                全局布局为垂直

android:orientation="horizontal"            全局布局为水平

布局分为三种

  • LinearLayout        线性布局

注:这里有个属性layout_weight:这是该属性占当前组件中的权重,也就是占比

  • RelativeLayout     相对布局

  • ConstraintLayout  约束布局

 滚动菜单ListView

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
public class MainActivity extends AppCompatActivity {

    private String[] data = {"Apple","Banana","Orange","Watermelon","Pear","Grape","Strawberry","Cherry","Mango",
            "Apple","Banana","Orange","Watermelon","Pear","Grape","Strawberry","Cherry","Mango",
            "Apple","Banana","Orange","Watermelon","Pear","Grape","Strawberry","Cherry","Mango"};

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

        //构建适配器对象
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,data);
        ListView listView = findViewById(R.id.list_view);
        listView.setAdapter(adapter);

    }
}

注:ListView需要使用适配器Adapter来创建骨架并传入数据 

比如

 现在右图的框架来自于安卓自带的框架

实现ListView的点击事件

注意,我们之前讲过,ListView的模板是安卓自带的,如果想要获取到里面的元素名字,就要使用其中自带的View属性TestView tv = view.findViewById(android.R.id.text1)就是你点击时当前的模板元素(这个是系统通过pisition参数来判断的),那么其名字就是tv.getText()

    private String[] fruitList = {"Apple","Banana","Orange","Watermelon","Pear","Grape","Strawberry","Cherry","Mango",
            "Apple","Banana","Orange","Watermelon","Pear","Grape","Strawberry","Cherry","Mango",
            "Apple","Banana","Orange","Watermelon","Pear","Grape","Strawberry","Cherry","Mango"};

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

        //构建适配器对象
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,fruitList);
        ListView listView = findViewById(R.id.list_view);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = view.findViewById(android.R.id.text1);
                Toast.makeText(MainActivity.this,tv.getText(),Toast.LENGTH_SHORT).show();

            }
        });
    }

定制ListView

我们让ListView可以显示图片

首先我们创建一个实体类作为适配器的适配类型

然后为创建一个布局

 

 然后自定义一个适配器

 现在来书写逻辑 

 实现定制ListView的点击事件

安卓系统访问网络系统时需要声明权限,否则会崩溃

可以在AndroidManifest.xml中设置权限

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐