android studio版本:
项目名称:optionmenu
这是关于我写的这个小东西的第三篇文章,也是最后一篇,包含全部代码,其他相关内容不值得再写,直接在本文里讲解备忘。
1、optionmenu;
2、activity之间跳转;
3、radiobutton android:checked="true"(选中);
4、edittext cityID.setVisibility(EditText.VISIBLE)(设定可见);
5、switch;
6、各activity之间数据传送。
先上代码(使用的是全屏布局):
第一屏代码fullscreenactivity.java、activity_fullscreen.xml、main.xml:
FullscreenActivity.java
/*
建立日期:2022.9.28
完成日期:2022年9月29日
包含内容:
0、optionmenu;
1、activity之间跳转;
2、radiobutton android:checked="true"(选中);
3、edittext cityID.setVisibility(EditText.VISIBLE)(设定可见);
4、switch;
5、各activity之间数据传送。
*/
package com.example.optionmenu;
import android.annotation.SuppressLint;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowInsets;
import android.widget.TextView;
import com.example.optionmenu.databinding.ActivityFullscreenBinding;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class FullscreenActivity extends AppCompatActivity {
/**
* Whether or not the system UI should be auto-hidden after
* {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private final Handler mHideHandler = new Handler(Looper.myLooper());
private View mContentView;
private TextView hf_key_xs;
private TextView cityID_xs;
private final Runnable mHidePart2Runnable = new Runnable() {
@SuppressLint("InlinedApi")
@Override
public void run() {
// Delayed removal of status and navigation bar
if (Build.VERSION.SDK_INT >= 30) {
mContentView.getWindowInsetsController().hide(
WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
} else {
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
}
};
private View mControlsView;
private final Runnable mShowPart2Runnable = new Runnable() {
@Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private boolean mVisible;
private final Runnable mHideRunnable = new Runnable() {
@Override
public void run() {
hide();
}
};
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
break;
case MotionEvent.ACTION_UP:
view.performClick();
break;
default:
break;
}
return false;
}
};
private ActivityFullscreenBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityFullscreenBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
mVisible = true;
mControlsView = binding.fullscreenContentControls;
mContentView = binding.fullscreenContent;
// Set up the user interaction to manually show or hide the system UI.
mContentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toggle();
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
binding.dummyButton.setOnTouchListener(mDelayHideTouchListener);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
private void toggle() {
if (mVisible) {
hide();
} else {
show();
}
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mControlsView.setVisibility(View.GONE);
mVisible = false;
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(mShowPart2Runnable);
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
private void show() {
// Show the system bar
if (Build.VERSION.SDK_INT >= 30) {
mContentView.getWindowInsetsController().show(
WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
} else {
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
}
mVisible = true;
// Schedule a runnable to display UI elements after a delay
mHideHandler.removeCallbacks(mHidePart2Runnable);
mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}
/**
* Schedules a call to hide() in delay milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//通过item.getItemId()对不同选项进行不同的处理
switch (item.getItemId())
{
case R.id.id_settings:
//事件
Intent intent = new Intent();
intent.setClass(FullscreenActivity.this,settings.class);
//startActivity(intent);
startActivityForResult(intent,0);
break;
}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("request代码"+requestCode+"result代码"+resultCode);
if (requestCode==0 &&resultCode == 1000) {
//使用Bundle接收数据
Bundle bundle = data.getExtras();
String key = bundle.getString("keyValue");
String id = bundle.getString("idValue");
hf_key_xs=(TextView)findViewById(R.id.hf_key_1);
hf_key_xs.setText(key);
cityID_xs=(TextView) findViewById(R.id.cityID_1);
cityID_xs.setText(id);
//取回单个数据
// //取出返回结果
// String string = data.getStringExtra("keyvalue");
// //将返回结果设置到textView上
// hf_key_xs=(TextView)findViewById(R.id.hf_key_1);
// hf_key_xs.setText(string);
// System.out.println("resultCode-"+data);
}
}
}
activity_fullscreen.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:background="?attr/fullscreenBackgroundColor"
android:theme="@style/ThemeOverlay.Optionmenu.FullscreenContainer"
tools:context=".FullscreenActivity">
<!-- The primary full-screen view. This can be replaced with whatever view
is needed to present your content, e.g. VideoView, SurfaceView,
TextureView, etc. -->
<TextView
android:id="@+id/fullscreen_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:keepScreenOn="true"
android:text="@string/dummy_content"
android:textColor="?attr/fullscreenTextColor"
android:textSize="50sp"
android:textStyle="bold" />
<!-- This FrameLayout insets its children based on system windows using
android:fitsSystemWindows. -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:id="@+id/fullscreen_content_controls"
style="@style/Widget.Theme.Optionmenu.ButtonBar.Fullscreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:orientation="horizontal"
tools:ignore="UselessParent">
<Button
android:id="@+id/dummy_button"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/dummy_button" />
</LinearLayout>
<TextView
android:id="@+id/hf_key_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_marginTop="100dp"
android:layout_marginLeft="30dp"
android:text="TextView" />
<TextView
android:id="@+id/cityID_1"
android:layout_marginTop="140dp"
android:textSize="20sp"
android:layout_marginLeft="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</FrameLayout>
</FrameLayout>
main.xml(存放菜单项):
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<!-- app:showAsAction="always" 表示是显示三个点还是直接显示title,删掉显示三个点 -->
<item
android:id="@+id/id_settings"
app:showAsAction="always"
android:title="设置"
android:orderInCategory="1"
/>
</menu>
注意:这其中有两行会导致显示不同:
如果是这样:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- app:showAsAction="always" 表示是显示三个点还是直接显示title,删掉显示三个点 -->
<item
android:id="@+id/id_settings"
app:showAsAction="always"
android:title="设置"
app:showAsAction="always"
android:orderInCategory="1"
/>
</menu>
没有红色部分,则显示是三点,增加红色代码直接显示菜单项。我这个项目只有一个设置项,所以直接显示就可以,如果有多个菜单项,最好是三个点(下图是为了显示需要,并非本例代码显示结果)。显示如下图:
第一屏模拟器截图:
内容说明:
设置按钮跳转到第二个页面。
两个textview分别接收显示传回的数据。
一个main.xml保存菜单项。
第二屏代码settings.java、settings.xml:
settings.java
package com.example.optionmenu;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import androidx.appcompat.app.AppCompatActivity;
public class settings extends AppCompatActivity {
private Button button;
private Switch switch_hefeng;
private EditText hf_key;
private EditText cityID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settins);
switch_hefeng = (Switch) findViewById(R.id.switch_hefeng);
cityID=(EditText)findViewById(R.id.cityID);
hf_key=(EditText)findViewById(R.id.hf_key_1);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
switch_hefeng.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
cityID.setVisibility(EditText.VISIBLE);
hf_key.setVisibility(EditText.VISIBLE);
} else {
cityID.setVisibility(EditText.INVISIBLE);
hf_key.setVisibility(EditText.INVISIBLE);
}
}
});
//把key和cityID传值给FullscreenActivity
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Key =hf_key.getText().toString();
String Id =cityID.getText().toString();
//监听器要做的事情
Intent intent=new Intent(settings.this,FullscreenActivity.class);
Bundle bundle=new Bundle();
bundle.putString("keyValue",Key);
bundle.putString("idValue",Id);
intent.putExtras(bundle);
setResult(1000,intent);
//传单个数据
// intent.putExtra("keyvalue",Key);
// //设置返回结果,将“ExtraData”的值 通过intent返回
// setResult(1000,intent);
finish();
}
});
}
}
settings.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="20dp" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="235dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:text="完成"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.465"
app:layout_constraintStart_toStartOf="@+id/guideline2" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="437dp" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="@+id/guideline3"
app:layout_constraintEnd_toStartOf="@+id/guideline5"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="桌面模式(适合近距离使用)"
android:textSize="20sp" />
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:text="客厅模式(适合远距离使用)"
android:textSize="20sp" />
</RadioGroup>
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="395dp" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(如无和风帐号请勿打开)"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="@+id/guideline6"
app:layout_constraintEnd_toStartOf="@+id/guideline5"
app:layout_constraintHorizontal_bias="0.549"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline3"
app:layout_constraintVertical_bias="0.722" />
<Switch
android:id="@+id/switch_hefeng"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:minHeight="48dp"
android:text="启用和风天气"
android:textSize="20sp"
android:textOff="关"
android:textOn="开"
android:checked="false"
app:layout_constraintEnd_toStartOf="@+id/guideline5"
app:layout_constraintHorizontal_bias="0.54"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline3" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="334dp" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="284dp" />
<EditText
android:id="@+id/hf_key_1"
android:layout_width="360dp"
android:layout_height="49dp"
android:ems="10"
android:inputType="textPersonName"
android:minHeight="48dp"
android:selectAllOnFocus="true"
android:text="和风key"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline5"
app:layout_constraintHorizontal_bias="0.387"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toTopOf="@+id/guideline6"
app:layout_constraintVertical_bias="0.02" />
<EditText
android:id="@+id/cityID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="108dp"
android:ems="10"
android:inputType="number"
android:selectAllOnFocus="true"
android:singleLine="true"
android:text="9位城市代码"
android:textSize="20sp"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline5"
app:layout_constraintHorizontal_bias="0.509"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline6"
app:layout_constraintVertical_bias="0.22" />
</androidx.constraintlayout.widget.ConstraintLayout>
模拟器截图:
内容说明:
模式选择是为我另一个项准备的,此处无代码。
启用用风天气关闭的时候下面两个editview是不显示的,打开的时候显示,输入数据后,点击完成,将数据(key和传回到fullscreenactivity.java,并关闭这个页面。
跳转关键代码:
跳转到第二个activity的代码使用startActivityForResult(intent,0);
我在网上看了挺多文章,很多文章里没有写这个,我没写实现不了逆跳转,让我很不理解,也让我走了些弯路,到底要不要写我也不知道,反正我这个项目写了就成功了,不写就不行。而且启动第二个activity也不是用startActivity(intent);那个0就是后面重写onActivityResult里面需要的requestcode,如果没有这个startActivityForResult(intent,0);requestcode是-1,所以是不可能收到回传数据的。而那个resultcode就是在第二个activity里面指写的。
fullscreenactivity.java 重写onActivityResult.
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("request代码"+requestCode+"result代码"+resultCode);
if (requestCode==0 &&resultCode == 1000) {
//使用Bundle接收数据
Bundle bundle = data.getExtras();
String key = bundle.getString("keyValue");
String id = bundle.getString("idValue");
hf_key_xs=(TextView)findViewById(R.id.hf_key_1);
hf_key_xs.setText(key);
cityID_xs=(TextView) findViewById(R.id.cityID_1);
cityID_xs.setText(id);
//取回单个数据
// //取出返回结果
// String string = data.getStringExtra("keyvalue");
// //将返回结果设置到textView上
// hf_key_xs=(TextView)findViewById(R.id.hf_key_1);
// hf_key_xs.setText(string);
// System.out.println("resultCode-"+data);
}
}
settings.java 按钮的onclick事件加入相关回传数据代码。
我要传的是两条数据所以用的是bundle,如果传单条数据就简单的多。
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Key =hf_key.getText().toString();
String Id =cityID.getText().toString();
//监听器要做的事情
Intent intent=new Intent(settings.this,FullscreenActivity.class);
Bundle bundle=new Bundle();
bundle.putString("keyValue",Key);
bundle.putString("idValue",Id);
intent.putExtras(bundle);
setResult(1000,intent);
//传单个数据
// intent.putExtra("keyvalue",Key);
// //设置返回结果,将“ExtraData”的值 通过intent返回
// setResult(1000,intent);
finish();
}
});
其他细节:
1、重写public boolean onOptionsItemSelected(MenuItem item) {}
public boolean onOptionsItemSelected(MenuItem item) {
//通过item.getItemId()对不同选项进行不同的处理
switch (item.getItemId())
{
case R.id.id_settings:
//事件
Intent intent = new Intent();
intent.setClass(FullscreenActivity.this,settings.class);
//startActivity(intent);
startActivityForResult(intent,0);
break;
}
return true;
}
startActivityForResult(intent,0);被画上了删除线,说明现在已经不用这个方法了,但别的我也不会,好在它还能正常工作。
2、bundle用法,很多资料,用法简单,此处不讲。
3、radiobutton android:checked="true"(选中);单选按钮,如果不加这一条是不会有默认选中项的。
4、edittext cityID.setVisibility(EditText.VISIBLE)(设定可见);edittext是不可设定不可编辑的,只能设置是否可见。这里个例程里,如果不打开开关即设置为不可见。(其实里面有bug,即使不可见,也会把默认值传过去,暂时没改)