簡體   English   中英

從MainActivity更新片段內的textview

[英]Update textview inside fragment from MainActivity

這是我的第一個stackoverflow帖子。
我正在嘗試構建一個應用程序,該應用程序使用LocalBroadcastManager檢索傳感器數據,然后在容器內已連接的片段中更新TextView。
我嘗試從MainActivity調用方法homeFragment.passData(),但未成功。
我的猜測是,該片段已經膨脹,因此無法通過調用該方法進行更新。

這是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?
我希望我的問題是可以理解的。 謝謝

您需要在片段中設置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!");

    ...

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM