xml学一些基本的就可以,实际应用中我们可以用UI界面操作(其实Androidstudio也是有UI界面的)
这样还能让我对于开发产生点兴趣,否则写代码太抽象了,一点意思没有。我就放弃了
一般我都不看代码视图,当然代码敲得很6的除外
关于逻辑方面我们要编写的是java的文件
1.先给文字添加一个id
2.然后获取这个页面的id
3.然后改变文本内容
添加ID我们在设计视图就可以添加啊
然后代码视图就变成了这样
然后我们编辑MainActivity文件
package com.weijun901.app;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建一个TextView对象,通过findViewById方法得到TextView对象id为hello的值,给hello变量
TextView hello = findViewById(R.id.hello);
//使用setText()方法修改文本
hello.setText("Hello,My World!");
}
}
果然Hello World!
变成了Hello,My World!
这是在项目初始化完毕的时候,文字就自动改变了。
如果想点击按钮后改变呢?
我们需要在前端添加一个按钮,并且给按钮也加个id
当我尝试修改的按钮上的文字的时候,把"button"改成"改变"的时候,软件提示我要提取字符串资源,我不明白是啥意思,现在明白了。
它是把按钮的文字当成了字符串数据,一起汇总到了这里
就是这个文件夹下的xml文件,点开看看,就是这个结构
点开编辑,还可以手动进行添加,用于管理字符串资源数据,看来按钮的text属性是按照字符串自动打包的
不用管它,我们继续,修改MainActivity文件
package com.weijun901.app;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建一个TextView对象,通过findViewById方法得到TextView对象id为hello的值,给hello变量
TextView hello = findViewById(R.id.hello);
//创建一个Button对象,
Button button1 = findViewById(R.id.button1);
//对按钮点击事件进行监听,按钮被点击时,改变id为hello的文本内容
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
//使用setText()方法修改文本
hello.setText("Hello,My World!");
}
});
}
}
软件给了个黄叹号提示
我点击右键显示快速修复,替换为lambda
发现了语法糖,箭头函数
之前这样
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
//使用setText()方法修改文本
hello.setText("Hello,My World!");
}
});
现在变成了这样
button1.setOnClickListener(v -> {
//使用setText()方法修改文本
hello.setText("Hello,My World!");
});
省了好多啊,我去,还真好用
重载一下,果然点击按钮进行了改变
如果想点击按钮,两个文字来回变呢?
直接贴代码了
activity_main.xml
MainActivity
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//上面的内容不用管它,那是页面初始化的内容
//我们也要在页面初始化里面写个内容,以方便展示
TextView hello = findViewById(R.id.hello);
//创建一个TextView对象,通过findViewById方法得到TextView对象id为hello的值,给hello变量
Button button = findViewById(R.id.button);
//创建一个Button对象,通过findViewById方法得到Button对象id为button的值,给button变量
//对按钮点击事件进行监听,按钮被点击时,改变id为hello的文本内容
button.setOnClickListener(v -> {
int num = (int) (Math.random()*100);
hello.setText(String.valueOf(num));
});
}
}
换了个手机



