java - setOnClickListener 不适用于膨胀布局
问题描述
我在子布局中制作的按钮不起作用。我希望我的 button_sub 在我点击时工作。我认为layer inflater有问题,但我还是不明白
final View addedView =inflater.inflate(R.layout.sublayout,null);
如何修改我的代码?
这是我的 MainActivity 类
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button3by3 = findViewById(R.id.button_3by3);
container=findViewById(R.id.container);
button3by3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addedView =inflater.inflate(R.layout.sublayout,null);
container.addView(addedView);
}
});
}
这是我的主要活动 xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="154dp"
tools:layout_editor_absoluteY="138dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toast"
android:id="@+id/button_sub"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
最后是我的子布局活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sublayout);
btn_sub=findViewById(R.id.button_sub);
textView = findViewById(R.id.textView);
btn_sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(subAction.this, "Hello", Toast.LENGTH_SHORT).show();
textView.setText("HELLLLLOOOO");
}
});
}
解决方案
您可以尝试在 onCreateView 内部进行充气操作,或者您唯一的问题是
直接使用 getSystemService 而不使用 getContext 所以首先创建 Context 上下文
然后在此上下文中使用 getSystemService 将是另一种选择。
在活动中你可以尝试;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
inflater =(LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View addedView = inflater.inflate(R.layout.sublayout,container,false);
button3by3 = addedView.findViewById(R.id.button_3by3);
button3by3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//related code comes here
}
});
return addedView;
}
}
PS:您也可以在片段中尝试这些。
推荐阅读
- r - 计算跨特定行的数据帧内的相似性 (R)
- python - 如何让我的线性回归模型使用 clf.predict 进行预测?
- asp-classic - ASPupload 'if Not File Is Nothing' 总是返回 false
- python - FileNotFoundError: [Errno 2] 没有这样的文件或目录 - 无法解决路径问题
- html - Blazor - 使 InpuText 适合父容器
- sql-server - 为什么 Datagrip 在 Tableplus 中工作时会说用户/传递错误?
- r - 如何使包含 NA 的函数准确工作?
- html - 删除图像之间不需要的间隙
- image - 如何确定应用程序使用的图像大小?
- vue.js - 为此图像滑块设置大小和位置道具的最佳方法是什么?