【问题标题】:android setting textview from another class with Fragmentsandroid从另一个带有片段的类设置textview
【发布时间】:2014-11-06 16:49:39
【问题描述】:

我正在尝试设置另一个类的 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 {

由于某种原因,当我尝试使用其他类设置文本视图时

DemoActivity.textViewObj5.setText(c.getString(5));

它给出了错误:DemoActivity 无法解析

有什么想法吗?

我们一如既往地感谢您的帮助

标记

【问题讨论】:

  • 您不能将视图称为静态视图,因为您在 DemoActivity 中的视图仅在创建 DemoActivity 的实例时创建。
  • 我不明白你的意思。当您使用 Extends Activity 时,它可以正常工作

标签: android class android-fragments textview


【解决方案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() 方法中实现所需的接口

【讨论】:

  • 非常感谢,虽然我没有使用 n 接口,但它让我更好地理解了片段,这使我能够使我现有的代码工作
【解决方案2】:

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

【讨论】:

  • 我尝试使用 DemoActivity.getActivity().textViewObj1.setText(c.getString(1));但它仍然说无法解决
猜你喜欢
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多