android使用Fragments从另一个类设置textview

时间:2014-11-06 16:49:40

标签: android class android-fragments textview

我试图从另一个类设置textview文本 textview在主要活动中,我需要从另一个不是活动的类中设置它

过去我使用过以下内容

public class DemoActivity extends Activity {
public static TextView textViewObj1;
public static TextView textViewObj2;
public static TextView textViewObj3;
public static TextView textViewObj4;
public static TextView textViewObj5;


public void onCreate(final Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);      
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    textViewObj1 = (TextView) findViewById(R.id.Sitename);
    textViewObj2 = (TextView) findViewById(R.id.Building);
    textViewObj3 = (TextView) findViewById(R.id.Floor);
    textViewObj4 = (TextView) findViewById(R.id.Roomno);
    textViewObj5 = (TextView) findViewById(R.id.Drawref);

然后我使用

在另一个类中设置它
    DemoActivity.textViewObj1.setText(c.getString(1));
    DemoActivity.textViewObj2.setText(c.getString(2));
    DemoActivity.textViewObj3.setText(c.getString(3));
    DemoActivity.textViewObj4.setText(c.getString(4));
    DemoActivity.textViewObj5.setText(c.getString(5));

我遇到的问题是应用程序我试图将其设置为使用片段,因此主要活动而不是像这样开始

  public class DemoActivity extends Activity {

像这样开始

  public class DemoActivity extends FragmentActivity {

出于某种原因,当我尝试使用

从其他类设置textview时
DemoActivity.textViewObj5.setText(c.getString(5));

它给出错误:无法解析DemoActivity

任何想法?

一如既往地感谢您的帮助

标记

2 个答案:

答案 0 :(得分:1)

最佳做法是:

1)在片段中定义一个监听器接口

public interface FragmentInteractionListener{
   void onFragmentInteraction(String textToPut);
}

2)在parentActivity中实现此接口:

public class MyParentActivity extends Activity implements FragmentInteractionListener {
...

   @Override
   public void onFragmentInteraction(String textToPut) {
      //Update the textView here
   }

3)在你的片段中,调用父Activity方法:

((FragmentInteractionListener )getActivity()).onFragmentInteraction("This is the new text");

您可能想要检查父活动是否在片段的onAttach()方法中实现所需的接口

答案 1 :(得分:0)

尝试使用DemoActivity.getActivity()或this.getActivity()。我知道在使用活动时,我们只是调用上下文,但使用片段涉及使用getActivity.Hope这有助于