可以在片段访问其活动的GUI中编码吗?

时间:2016-01-04 20:23:44

标签: android android-fragments

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<fragment
  android:id="@+id/fragment1"
  android:name="ankit.fairmatrix.in.MyListFragment"
  android:layout_width="match_parent"
  android:layout_height="match_parent" />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
android:id="@+id/mText"
    android:text="Hello World!" />
     </LinearLayout> 

如何从Fragment类MyListFragment中访问活动内部的TextView(此处为mText)?

1 个答案:

答案 0 :(得分:0)

 (TextView) ((MyActivity)getActivity).findViewById(R.id.mText);

但最好做这样的事情:

public class MainActivity extends Activity implements OnTextChangeListener {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id. mText);
    }

    @Override
    public void changeText(String text){
       textView.setText(text);
    }
 }

片段代码

public class MyListFragment extends Fragment {

   interface OnTextChangeListener{
     void changeText(String text);   
   }

private OnTextChangeListener onTextChangeListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof OnTextChangeListener){
            onTextChangeListener = (OnTextChangeListener)activity;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.chat_list, container, false);
    }

    public void something(){
      onTextChangeListener.change("Hello");
    }
 }