gpt4 book ai didi

android - OnClickListener 不适用于 Fragment

转载 作者:行者123 更新时间:2023-11-30 01:11:07 25 4
gpt4 key购买 nike

我试用 Fragment 时发现 OnClickListener 有问题。任何人都可以帮忙吗?

主 Activity .java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frag_one frag1=new frag_one();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.top,frag1,"");
transaction.commit();
}
}

frag_one.java

public class frag_one extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_frag_one,container,false);
}

public class calculator extends AppCompatActivity implements View.OnClickListener {
TextView get_result;
EditText get_num1;
EditText get_num2;
Button get_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frag_one);
get_result=(TextView)findViewById(R.id.result);
get_num1=(EditText) findViewById(R.id.num1);
get_num2=(EditText) findViewById(R.id.num2);
get_button=(Button)findViewById(R.id.submit);
get_button.setOnClickListener(this);
}
public void onClick(View v) {
int num1=Integer.parseInt((get_num1.getText().toString()));
int num2=Integer.parseInt((get_num2.getText().toString()));
int sum=num1+num2;
get_result.setText(Integer.toString(sum));
}
}
}

当我在不使用 Fragment 的情况下进行正常 Activity 时。当我单击按钮时,计算有效。但是当我移动到 Fragment 时,它不起作用。请帮忙!谢谢

enter image description here

最佳答案

您创建了第二个 Activity,它使用 Fragment 的布局而不是实际将逻辑放入 Fragment 类中....

public class frag_one extends Fragment implements View.OnClickListener {

TextView get_result;
EditText get_num1;
EditText get_num2;
Button get_button;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_frag_one,container,false);

get_result=(TextView)rootView.findViewById(R.id.result);
get_num1=(EditText)rootView.findViewById(R.id.num1);
get_num2=(EditText) rootView.findViewById(R.id.num2);
get_button=(Button)rootView.findViewById(R.id.submit);
get_button.setOnClickListener(this);

return rootView;
}

public void onClick(View v) {
// TODO: Check v.getId() == R.id.submit
int num1=Integer.parseInt((get_num1.getText().toString()));
int num2=Integer.parseInt((get_num2.getText().toString()));
int sum=num1+num2;
get_result.setText(Integer.toString(sum));
}
}

关于android - OnClickListener 不适用于 Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38418508/

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