如何将片段中的值设置为其他活动

时间:2019-05-23 15:41:19

标签: java android android-fragments android-activity layout-inflater

我正在android studio中创建一个应用程序,在其中我可以从服务器中的片段中获取一些数据。但是我希望这些数据在另一个不同的活动中显示。我尝试使用LayoutInflater执行任务,但收到错误。我是一名初级开发人员,这对我来说是个新话题,我尝试过寻找解决方案,但没有一个起作用。 请协助。

1.my fragment Codes

//These are some of my instance variables
public ImageView imageV;
public TextView txtV;
public LinearLayout linearLayout;




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

    mAuth= FirebaseAuth.getInstance();


        inflater = (LayoutInflater) getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        View myLayout = inflater.inflate(R.layout.activity_project_view, (ViewGroup) view, false);
        linearLayout = (LinearLayout) view.findViewById(R.id.linearlayout);

        imageV = (ImageView) myLayout.findViewById(R.id.imageV);
        txtV = (TextView) myLayout.findViewById(R.id.txtV);..............


//Below is the onClick method Where I want those data to be displayed 
  //to another activity.


  @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

 DataSnapshot  myDataSnapShot  = uids.get(position);

  String Downloaduri = (String) myDataSnapShot.child("ImageLink").getValue();
  String title = (String) myDataSnapShot.child("Title").getValue();

    txtV.setText(title);

  Picasso.get().load(Downloaduri).into(imageV, new com.squareup.picasso.Callback() {………... }
      linearLayout.addView(imageV);
      linearLayout.addView(txtV);



2. xml file of another activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ProjectView">

<LinearLayout
    android:layout_width="match_parent"
    android:id="@+id/linearlayout"
    android:layout_height="match_parent"
    android:orientation="vertical" >



<ImageView
    android:id="@+id/imageV"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_gravity="center"
    android:layout_centerHorizontal="true"
    app:srcCompat="@drawable/wheel" />

<TextView
    android:id="@+id/txtV"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/imageV" />
</LinearLayout>

1 个答案:

答案 0 :(得分:0)

首先,您必须开始活动,否则您将获得Null

Intent intent = new Intent(Objects.requireNonNull(getActivity()).getBaseContext(),
            ExampleActivity.class);

然后,您可以将数据传递给目标Activity中的任何方法,例如此示例

((ExampleActivity)getContext()).parsData(data);