togglebutton
转帖请注明本文出自weimeig的博客(https://blog.csdn.net/weimeig/article/details/79663037),请尊重他人的辛勤劳动成果,谢谢
应朋友们反馈的Android基础薄弱的问题,决定出一套Android基础教程,帮助大家复习,巩固Android基础,今天要讲的是Android中的ToggleButton开关按钮。
布局文件 activity_togglebutton.xm
<?xml version="1.0" encoding="utf-8"?>
<Linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="你今天开心吗?"/>
<ImageView
android:id="@+id/hAPPy_iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"/>
<ToggleButton
android:id="@+id/tb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:textOff="不开心"
android:textOn="开心"/>
</LinearLayout>
java文件
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.radiobutton;
import android.widget.radiogroup;
import android.widget.TextView;
import android.widget.toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private ToggleButton mToggleButton;
private TextView mTextView;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedinstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_togglebutton);
mImageView = findViewById(R.id.happy_iv);
mToggleButton = findViewById(R.id.tb);
mToggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mToggleButton.isChecked()){
toast.maketext(MainActivity.this,mToggleButton.getText().toString(),1000).show();
mImageView.setImageResource(R.mipmap.ic_launcher);//设置ImageView控件图片所显示的内容
}else{
Toast.makeText(MainActivity.this,mToggleButton.getText().toString(),1000).show();
mImageView.setImageResource(R.drawable.ic_launcher_foreground);//设置ImageView控件图片所显示的内容
}
}
});
}
}
相关阅读
示例图:activity.xml文件布局<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android