将文本视图数据从mainactivity获取到片段

mwg9r5ms  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(325)

我想获取textview信息以分割textview。
主要活动:

public final DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                Calendar c = Calendar.getInstance();
                c.set(Calendar.YEAR, year);
                c.set(Calendar.MONTH, month);
                c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                String format = new SimpleDateFormat("dd/MM/yyyy").format(c.getTime());
                datePicker1.setText(format);
Tab1_fragment.getInstance().setText(Integer.toString(difference(c.getTimeInMillis())));

            }
        };

片段:

public class Tab1_fragment extends Fragment {
        TextView betweendate;
        public void setText (String text){
            TextView betweendate = (TextView) this.getView().findViewById(R.id.betweenDate);
            betweendate.setText(text);
        }

我做得对吗?日志中的结果为:
尝试在空对象引用上调用虚拟方法“android.view.view android.view.view.findviewbyid(int)”

ifmq2ha2

ifmq2ha21#

首先在oncreateview(片段)中定义所有视图(textview和…),它们的初始视图如下所示:

@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_compare_result, container, false);
    initView(view);
    return view;

}
private void initView(View view) {
    txtProductName = view.findViewById(R.id.txt_product_name);
    txtProductc = view.findViewById(R.id.txt_product_c);
    txtProductn = view.findViewById(R.id.txt_product_n);

    }

要将活动中的数据发送到片段,可以使用contracture片段获取数据或意图

svmlkihl

svmlkihl2#

初学者的简单实现如下所示:
您可以从片段中访问活动数据:

Activity:

public class YourActivity extends Activity {

    private String myString = "hello";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        ...
    }

    public String getDataLocal() {
        return myString;
    }
}

Fragment:

public class MyFragment extends Fragment {
    TextView tv;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {=

        View view = inflater.inflate(R.layout.frgament_layout_view, container, false);
        tv = (TextView) view.findViewById(R.id.yout_text_view);

        return view;
    }

    @Override
    public View onViewCreated(..) {

        YourActivity activity = (YourActivity) getActivity();
        String myActivityData = activity.getDataLocal();
        tv.setText(myActivityData);

        return view;
    }
}

希望这能让您了解如何将数据从活动发送到片段。
第二个解决方案:从 YourActivity ```
var fragment = supportFragmentManager.findFragmentById(YOUR_FRAG_ID) as MyFragment
fragment.updateMyData(YOUR_NEW_DATA);

尝试第二种解决方案,它应该会起作用。:)

相关问题