第一个app
app示例
说明
主要设计layout布局,log cat日志,Toast日志
layout代码
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#C8FF00"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:background="#00FF90"
android:orientation="vertical"
android:padding="10dp"
tools:ignore="Suspicious0dp">
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:text="I am a text"
android:textColor="@color/black"
android:textSize="30sp"
android:layout_weight="1"
android:gravity="center"
android:layout_gravity="center_horizontal|center_vertical">
</TextView>
<Button
android:id="@+id/button_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_gravity="center"
android:text="btn1"
android:textSize="30sp">
</Button>
</LinearLayout>
</LinearLayout>
java部分事件代码
MainActivity.java
package com.example.helloword2;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = findViewById(R.id.button_view);
TextView text1 = findViewById(R.id.text_view);
btn1.setOnClickListener(new MyBtnOneClickLisener());
}
class MyBtnOneClickLisener implements View.OnClickListener {
@Override
public void onClick(View v) {
if (v.getId() == R.id.button_view) {
TextView tx1 = findViewById(R.id.text_view);
String tx1_text;
tx1_text = (String) tx1.getText();
if (tx1_text.equals("Hello,Ninghao!")) {
tx1.setText("I am a text");
}
if (tx1_text.equals("I am a text")) {
tx1.setText("Hello,Ninghao!");
}
String is_same = "False";
Toast.makeText(MainActivity.this, is_same, Toast.LENGTH_SHORT).show();
Log.d("tx1_text", tx1_text);
}
}
}
}