2017-10-21 108 views
0

这是我的第一个stackoverflow帖子。
我试图建立一个应用程序,它用LocalBroadcastManager检索传感器数据,然后在中更新TextView已经连接容器内的片段。
我试图从MainActivity调用homeFragment.passData()方法,但没有成功。
我的猜测是因为片段已经膨胀了,所以不能通过调用该方法来更新。

这里是MainActivity代码,我调用方法来更新TextView的从MainActivity更新textview内部片段

@Override 
    public void onReceive(Context context, Intent intent) { 
     String azimuthValue = intent.getStringExtra("azimuth"); 
     String pitchValue = intent.getStringExtra("pitch"); 
     String rollValue = intent.getStringExtra("roll"); 


     homeFragment.passData(azimuthValue, pitchValue, rollValue); 
    } 


,这里是为HomeFragment

public class HomeFragment extends Fragment { 

private static final String TAG = "HomeFragment"; 

private Context mContext; 

private TextView xValueTextView; 
private TextView yValueTextView; 
private TextView zValueTextView; 

private OnFragmentInteractionListener mListener; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_home, container, false); 

    xValueTextView = (TextView) rootView.findViewById(R.id.xValueTextView); 
    yValueTextView = (TextView) rootView.findViewById(R.id.yValueTextView); 
    zValueTextView = (TextView) rootView.findViewById(R.id.zValueTextView); 

    Log.d(TAG, "onCreateView: layout inflated"); 

    return rootView; 
} 

@Override 
public void onAttach(Context context) { 
    super.onAttach(context); 
    mContext = context; 
} 

@Override 
public void onDetach() { 
    super.onDetach(); 
    mListener = null; 
} 

public interface OnFragmentInteractionListener {} 

public void passData(String x, String y, String z) { 
    xValueTextView.setText(x); 
    yValueTextView.setText(y); 
    zValueTextView.setText(z); 

    Log.i(TAG, "updateTextView: TextView value: " + xValueTextView.getText().toString() + "||" + yValueTextView.getText().toString() + "||" + zValueTextView.getText().toString()); 
} 

代码}


虽然logcat的textview.getText( ).toString显示更新值,实际视图尚未更新

10-21 14:03:56.240 19338-19338/pro.adhi.willyam.orientation I/HomeFragment: updateTextView: TextView value: 45||-34||4 

这里是截图来自我的电话:https://i.stack.imgur.com/ZDsad.png

因此,如何正确地更新内部片段的TextView像我想要达到什么目的?
我希望我的问题是可以理解的。 Thankyou

+0

只使用一个回调,它会调用你的UI中的片段,或者您可以使用片段的静态对象。但我提到你使用回调 –

+0

即时通讯不能确定你的意思,你可以更具体请拨打 – fullmoon6661

回答

0

您需要在片段中设置setter/getter方法。

public class HomeFragment extends Fragment { 

TextView tv; 

    public void setTextView(String text) 
    { 
     TextView tv = (TextView) findViewById(*your id here*); 
     tv.setText(text); 
    } 
} 

在MainActivity你只需要使用此电话:

public class MainActivity extends AppCompatActivity { 

    ... 

    HomeFragment.setTextView("Hello World!"); 

    ... 

} 
+0

调用findviewbyid里面的片段而不指定视图将返回null。但我仍然会尝试一下 – fullmoon6661