我正在尝试从EditTexts中获取字符串,并在按钮上单击微调器以单击片段。
我已经在一个活动中编写了一些代码,并且可以正常工作,但是我不知道如何更改它,因此它可以在一个片段中工作。
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));
}
活动中的代码与不和谐应用共享一个字符串。我为该片段尝试的每次修改都会使应用程序崩溃。
感谢您的帮助。
首先,您无法像活动一样处理片段中的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;
}
我希望有帮助。