我想从片段获取数据到主活动,我的数据位于片段中,当我单击主活动上的按钮时,我需要在主活动中获取该数据
我从 StackOverflow 找到了一个解决方案,就在这里。
public void getFromUser(View view) {
ConversationFragment fragment1 = (ConversationFragment)getSupportFragmentManager().findFragmentById(R.id.container);
View frag=fragment1.getView();
EditText editText1 =(EditText) frag.findViewById(R.id.message);
String message=editText1.getText().toString();
sendMessage(message);
}
但很少有人提到这是一个不好的做法,然后我听说用界面做类似的事情,我是Java新手,所以有人可以提到一个使用按钮从片段获取数据到主活动的示例吗单击主要活动
为此使用 ViewModel:https://developer.android.com/guide/fragments/communicate 然后你可以观察数据的变化并用它做任何你想做的事。
是的 onAttachFragment 已从 Android 9 弃用,您可以使用其他方法来实现类似的功能,具体取决于代码的上下文。但目前还不需要
ConversationFragment.java:
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import androidx.fragment.app.Fragment;
public class ConversationFragment extends Fragment {
private EditText editText;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_conversation, container, false);
// Initialize EditText
editText = view.findViewById(R.id.editText);
return view;
}
public String getEditTextValue() {
return editText.getText().toString();
}
}
MainActivity.java:
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private ConversationFragment conversationFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the fragment
conversationFragment = new ConversationFragment();
// Add the fragment to the container
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, conversationFragment)
.commit();
// Initialize Button
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get EditText value from the Fragment
String editTextValue = conversationFragment.getEditTextValue();
onDataReceivedFromFragment(editTextValue);
}
});
}
public void onDataReceivedFromFragment(String data) {
// Process the received data here
Log.d("Data received in Activity", data);
}
}
确保您还相应地更新布局文件(fragment_conversation.xml 和 Activity_main.xml)。