gpt4 book ai didi

java - addListener 按钮在 android studio 中的 fragment 中不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:18 25 4
gpt4 key购买 nike

这是 fragment 代码,我在这里尝试了各种方法来实现按钮监听器,但没有一个起作用。我尝试过 addListenerOnbutton、OnClick 方法,并尝试在 mainactivity 中使用此代码。但它们都没有真正起作用。任何建议都可以对我有很大帮助。

   public class tab2 extends Fragment implements View.OnClickListener{

Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19;
View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {


addListenerOnButton();

// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab2, container, false);
}

void addListenerOnButton(){

/*b1 = getView().findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("Error has occurred");
}
});*/
/* b1 = getView().findViewById(R.id.b1);
b3 = getView().findViewById(R.id.b3);
b4 = getView().findViewById(R.id.b4);
b5 = getView().findViewById(R.id.b5);
b6 = getView().findViewById(R.id.b6);

b1.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
b5.setOnClickListener(this);
b6.setOnClickListener(this);*/
}


public void Activity1()
{
Intent intent = new Intent(getContext(),Activity1.class);
startActivity(intent);
}

....... until Activity19().....
@Override
public void onClick(View v)
{
/*switch (v.getId()){
case R.id.b1:
Activity1();
break;
case R.id.b3:
Activity3();
break;
case R.id.b4:
Activity4();
break;
case R.id.b5:
Activity5();
break;
case R.id.b6:
Activity6();
break;
}*/

}
}

最佳答案

尝试这样的事情

public class BlankFragment extends Fragment implements View.OnClickListener {

private Button b1, b2;

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
b1 = view.findViewById(R.id.b1);
b2 = view.findViewById(R.id.b2);

b1.setOnClickListener(this);
b2.setOnClickListener(this);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_blank, container, false);
}

private void callActivity(Class activity) {
startActivity(new Intent(getContext(), activity));
}

@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.b1:
callActivity(FirstActivity.class);
break;
case R.id.b2:
callActivity(SecondActivity.class);
break;
}
}

关于java - addListener 按钮在 android studio 中的 fragment 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60180329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com