java - Android应用片段----使用按钮触发另一个开关按钮
问题描述
我尝试了很多次并编写了以下代码。我想在片段中同时点击按钮触发切换按钮。并且文本将被更改。但是当我运行代码时,应用程序会崩溃。请帮我解决这个问题。谢谢!顺便说一句,我使用片段来实现活动。
片段扫描.java
public class ScanFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
// TODO: Rename and change types of parameters
private Button buttonSCAN;
boolean is_enable = true;
private Switch SwitchScan;
Switch sw;
public ScanFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static ScanFragment newInstance(String param1, String param2) {
ScanFragment fragment = new ScanFragment();
Bundle args = new Bundle();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_scan, container, false);
buttonSCAN = (Button)rootView.findViewById(R.id.buttonSCAN);
SwitchScan=(Switch) rootView.findViewById(R.id.switch_Below);
buttonSCAN.setOnClickListener(new View.OnClickListener(){
boolean on=((Switch)rootView).isChecked();
@Override
public void onClick(View v) {
if(is_enable == true)
{
is_enable = false;
buttonSCAN.setText("Turn on SCAN");
boolean on=true;
if(on){
}
}
else{
is_enable = true;
buttonSCAN.setText("Turn off SCAN");
boolean on=false;
if(!on){
}
}
sw.setEnabled(is_enable);
}
});
return rootView;
}
public void switchclick(View view){
}
片段扫描.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".ScanFragment">
<!-- TODO: Update blank fragment layout -->
<Switch
android:id="@+id/switch_Below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:showText="true"
android:textOff=" Scan on "
android:textOn=" Scan off "
/>
<Button
android:id="@+id/buttonSCAN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="end"
android:text="Turn on SCAN " />
</LinearLayout>
解决方案
您的代码有很多问题:
boolean on = ((Switch)rootView).isChecked();
你不能投到rootView
,Switch
把它改成boolean on = SwitchScan.isChecked();
sw.setEnabled(is_enable);
sw
从未初始化并且对此调用任何方法都会导致 NullPointerException,我认为您应该将其更改为正确的开关,SwitchScan
因此请将其更改为SwitchScan.setEnabled(is_enable);
理想情况下不应该setEnabled
但是setChecked
这些更改将修复您的崩溃问题。
推荐阅读
- c# - 根据给定的整数生成连续的 IPv4 地址
- python - 如何在 python 反应计时器中停止“输入垃圾邮件”
- python - 无法识别和操纵本网站的“弹出”建议好吗?
- xml - ODK 创建测试 - 我可以随机排序吗?
- vega-lite - 日期解析以及何时在 Vega Lite 中使用 utc/TimeUnits?
- java - 无法从 Eclipse springboot 应用程序访问 localhost:8080
- r - 解释类似(但不同)指定线性回归模型的标准误差:R
- math - 将直线的起点和终点修剪到它们进入/退出矩形的位置?
- vba - 使用 VBA 访问 Access 中的 ImportTextFile
- ansible - 如何在单个操作中检查所有主机的状况并通过/失败运行