Android Programming

控件和布局

1.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:text="I‘m a TextView" android:gravity="center" android:textSize="24sp" android:textColor="#00ff00" />
    <!-- 字体大小以sp为单位 -->

</LinearLayout>

 技术图片

 

2. 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="I‘m a Button"
        />

</LinearLayout>

运行结果:

技术图片

 

图中界面按钮显示的文字为text属性内内容的大写形式。通过设置textAllCaps属性,可以让界面按钮显示的文字和实际设置的text内容相同

<Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="I‘m a Button" android:textAllCaps="false"
        />

运行结果:

技术图片

 

2.1 注册按钮监听器

按钮监听器有两种注册方式,一种是使用匿名类注册:

技术图片

按下按钮,出现一个Toast

运行结果:

技术图片

 

另一种则是通过实现接口的方法来注册:

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);
    }
    
    @Override public void onClick(View v){ switch(v.getId()) { case R.id.button: // 在此处添加逻辑
                break; default: break; } }
}