我正在尝试从 EditTexts 获取字符串,并在 fragment 中点击按钮时使用 Spinner 获取字符串。
我在 Activity 中编写了一些代码并且可以工作,但我不知道如何更改它以便它在 fragment 中工作。
public void buttonClick (View view) {
Spinner stars = findViewById(R.id.starsSpinner);
String starsText = stars.getSelectedItem().toString();
EditText time = findViewById(R.id.editTime);
String timeText = time.getText().toString();
EditText location = findViewById(R.id.editLocation);
String locationText = location.getText().toString();
String space = " ";
String shareBody ="!r " + starsText + space + locationText + space + timeText;
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setClassName("com.discord", "com.discord.app.AppActivity$AppAction");
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, shareBody));
}
Activity 中的代码与不和谐应用程序共享一个字符串。我对 fragment 尝试的每一次修改都会导致应用程序崩溃。
感谢您的帮助。
最佳答案
首先,你不能像 Activity 一样处理 fragment 中的 onclick 所以你应该从 xml 中删除这一行:
android:onClick="someMethod"
之后在您的 fragment 中初始化您的按钮对象并调用 它的 setOnClickListener 方法。
看看这个:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView=inflater.inflate(R.layout.fragment_blank, container, false);
//using findViewById() in a Fragment
Button button=rootView.findViewById(R.id.button_id);
//handle onclick events for the button
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText time = rootView.findViewById(R.id.editTime);
}
});
return rootView;
}
我希望这会有所帮助。
关于java - 如何在 fragment 中单击按钮时检索 EditTexts 和 Spinners?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58262646/