常用控件

本文详细介绍了在Java中使用控件的方法,包括通过XML配置和直接在Java程序中调用两种方式。重点展示了如何在Android应用开发中,对TextView、Button、ImageButton和ToggleButton进行操作,并提供了实际的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

控件的使用方法一般有两种,一种是xml配置,一种是直接在java程序上调用。游戏开发很少使用xml配置。

java代码:

    public void onCreate(Bundle savedInstanceState) {//回调方法
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);//设置显示的View
        textView = (TextView) this.findViewById(R.id.textView);
        button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(this);//为button添加监听器
        imageButton = (ImageButton) this.findViewById(R.id.imageButton);
        imageButton.setOnClickListener(this);//为imageButton添加监听器
        toggleButton = (ToggleButton) this.findViewById(R.id.toggleButton);
        toggleButton.setOnClickListener(this);//为toggleButton添加监听器
    }
 public void onClick(View v) {//重写的事件处理回调方法
  if(v == button){//点击的是普通按钮
   textView.setText("您点击的是普通按钮");
  }
  else if(v == imageButton){//点击的是图片按钮
   textView.setText("您点击的是图片按钮");
  }
  else if(v == toggleButton){//点击的是开关按钮
   textView.setText("您点击的是开关按钮");
  }  
 }
}

xml代码:

<?xml version="1.0" encoding="utf-8" ?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">
  <TextView android:id="@+id/textView"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="您没有点击任何按钮" />
  <Button android:id="@+id/button"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="普通按钮" />
  <ImageButton android:id="@+id/imageButton"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:src="@drawable/img" />
  <ToggleButton android:id="@+id/toggleButton"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />
  </LinearLayout>

输出效果:

 

编写过程遇到的问题主要是 每个文件,图片名都要小写。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值