Android 从片段中获取编辑文本值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25134645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get edittext value from fragment
提问by Tolgay Toklar
I am using fragments,I have an edittext in fragment and I want to get value in main activity.
我正在使用片段,我在片段中有一个编辑文本,我想在主要活动中获得价值。
This is my fragment layout
这是我的片段布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#878787" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="dfgdfgdf"
android:textSize="20dp"
android:layout_centerInParent="true"
android:id="@+id/user_name"/>
<EditText
android:id="@+id/message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:text="G?nder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="getFromUser"
android:layout_marginTop="40dp"
/>
</RelativeLayout>
I am loading fragment with this function:
我正在使用此功能加载片段:
public void startChat(JsonObject user) {
FrameLayout layout = (FrameLayout)findViewById(R.id.container);
layout.setVisibility(View.VISIBLE);
Bundle bundle = new Bundle();
bundle.putString("name", user.get("name").getAsString());
sendTo=user.get("username").getAsString();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ConversationFragment conv = new ConversationFragment();
conv.setArguments(bundle);
fragmentTransaction.add(R.id.container, conv);
fragmentTransaction.commit();
viewPager.setVisibility(View.GONE);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayHomeAsUpEnabled(true);
}
And this is my fragment class
这是我的片段类
public class ConversationFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String name = getArguments().getString("name");
View rootView = inflater.inflate(R.layout.fragment_conversation, container, false);
TextView username=(TextView)rootView.findViewById(R.id.user_name);
username.setText(name);
return rootView;
}
}
As you can see when press the button main activity runs "getFromUser" function.I want to get edittext value in this function.How can I do this ?
如您所见,当按下按钮时,主要活动运行“getFromUser”功能。我想在此功能中获取 edittext 值。我该怎么做?
采纳答案by 0101100101
It's always the same procedure for these things. You can't access a fragment's views just like that. You need a callback method.
这些事情总是相同的程序。您不能像那样访问片段的视图。你需要一个回调方法。
Add this code to ConversationFragment:
将此代码添加到ConversationFragment:
private OnGetFromUserClickListener mListener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnGetFromUserClickListener ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnGetFromUserClickListener");
}
}
public void getFromUser(View v) {
if (mListener != null) {
EditText edit = (EditText)findViewById(R.id.message);
mListener.getFromUser(edit.getText().toString());
}
}
public interface OnGetFromUserClickListener {
void getFromUser(String message);
}
Make your MainActivity implement this interface. Replace getFromUser() inside MainActivitywith:
让你的 MainActivity 实现这个接口。将MainActivity 中的getFromUser() 替换为:
public void getFromUser(String message) {
sendMessage(message);
}
Done.
完毕。
Edit: Actually, using the XML-onClick attribute is currently bugged (see onClick inside fragment called on Activity): It links to the activity instead of the fragment. You have to set the click listener programmatically to make sure the code won't break at some point in the future. So give the button an ID inside the XML (e.g. get_from_user) and add this code to onCreateView inside ConversationFragment:
编辑:实际上,当前使用 XML-onClick 属性存在问题(请参阅onClick 内部对 Activity 调用的片段):它链接到活动而不是片段。您必须以编程方式设置点击侦听器,以确保代码在将来的某个时刻不会中断。因此,在 XML 中给按钮一个 ID(例如 get_from_user)并将此代码添加到ConversationFragment 内的 onCreateView:
v.findViewById(R.id.get_from_user).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getId() == R.id.get_from_user) {
getFromUser(v);
}
}
});
Using this code vastly decouples the activity and the fragment from each other.
使用此代码极大地将活动和片段彼此分离。
回答by Hardik Trivedi
There are Two approches
有两种方法
- Use of getActivity() Method
- getActivity() 方法的使用
In your fragment you can call getActivity(). This will give you access to the activity that created the fragment. From there you can obviously call any sort of accessor methods that are in the activity.
在您的片段中,您可以调用 getActivity()。这将使您可以访问创建片段的活动。从那里您显然可以调用活动中的任何类型的访问器方法。
class ParentActivity extends Activity
{
public void callFromFragment()
{
// Your business logic
}
}
class ChildFragment extends Fragment
{
public void callingMethod()
{
// This is how you call method of Activity from Fragment.
((ParentActivity)getActivity()).callFromFragment();
}
}
- Use of Interfaces
- 接口的使用
Create Interface. Implement is on Container Activity. Pass its reference to Fragment. Call the interface's method from Fragment.
创建接口。实施在容器活动上。将其引用传递给 Fragment。从 Fragment 调用接口的方法。
public interface Mediator {
public void callFromFragment();
}
class ParentActivity extends Activity implements Mediator
{
private void someMethod()
{
ChildFragment fragment=new ChildFragment();
fragment.setMediator(this);
// Fragmet Transaction lofi
}
@Override
public void callFromFragment()
{
}
}
class ChildFragment extends Fragment
{
Mediator mediator;
public Mediator getMediator() {
return mediator;
}
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
public void callingMethod()
{
// This is how you call method of Activity from Fragment.
mediator.callFromFragment();
}
}
回答by Tolgay Toklar
I resolved this problem.
我解决了这个问题。
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);
}
Now I can get edittext value from fragment.
现在我可以从片段中获取 edittext 值。