简体   繁体   English

片段TextView无法从可包裹对象更新

[英]Fragment TextView is not able to be updated from parcelable object

In my fragment, I have a textView which I want to set to a specific String. 在我的片段中,我有一个textView想要设置为特定的String。 I want to get the String for the textView from an object, which I send to the fragment as a parcelable. 我想从一个对象获取textView的字符串,并将其作为可打包的形式发送到片段。 I can retrieve the parcelable object and use the object to get the String (when I log it, the correct String is displayed). 我可以检索可包裹对象并使用该对象获取字符串(当我记录它时,将显示正确的字符串)。 But when I want to use this to set the textView, the textView doesn't change. 但是,当我想使用它来设置textView时,textView不会改变。

Any ideas why this happens and how I can fix it? 有什么想法为什么会发生以及如何解决?

Thanks! 谢谢!

Edit1: I added the activity the fragment is located in to, maybe the error is here? Edit1:我添加了片段所在的活动,也许错误在这里?

Edit2: I added the Data class (the parcelable object). Edit2:我添加了Data类(可打包对象)。 But removed the content of the constructor just to keep it easy to read. 但是删除了构造函数的内容只是为了使其易于阅读。

public class NavigationFragment extends Fragment {

    private static final String TAG = "NavigationFragment";

    public NavigationFragment() {
    }

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

        View view = inflater.inflate(R.layout.fragment_navigation, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
       Bundle bundle = this.getArguments();
        if(bundle!=null) {
            Data data = (Data) bundle.getParcelable("data");
            TextView stopTitle = (TextView) view.findViewById(R.id.stopTitle);
            final String name = data.getTourName();
            Log.d(TAG, name);
            stopTitle.setText(name);
        }
    }

}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    android:background="@color/colorAccent"
    tools:context=".DoTourActivity">

    <TextView
        android:id="@+id/stopTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:text="stopTitle"
        android:textSize="30dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="365dp"
        android:layout_height="158dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.492"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/stopTitle"
        tools:src="@drawable/placeholder_pic" />

    <TextView
        android:id="@+id/stopDescription"
        android:layout_width="384dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="24dp"
        android:text="stopDescriptionstopDescriptionstopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescriptionstopDescriptionstopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="395dp"
        android:layout_height="40dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="8dp"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/stopDescription">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@android:drawable/ic_menu_mylocation" />

        <TextView
            android:id="@+id/locationAdress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="locationAdress"
            android:textSize="23dp" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@android:drawable/ic_dialog_map" />

    </LinearLayout>

    <EditText
        android:id="@+id/pincode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:inputType="number"
        android:text="pincode"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout" />

    <Button
        android:id="@+id/confirmButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="confirm"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/pincode" />

</android.support.constraint.ConstraintLayout>
public class DoTourActivity extends AppCompatActivity {

    private static final String TAG = "DoTourActivity";

    private SectionStatePagerAdapter sectionStatePagerAdapter;
    private ViewPager viewPager;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_do_tour);

        //Fragment management
        sectionStatePagerAdapter = new SectionStatePagerAdapter(getSupportFragmentManager());
        viewPager = (ViewPager) findViewById(R.id.container);
        setupViewPager(viewPager);

        //Setup actionbar
        Toolbar myToolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(myToolbar);


        //get chosen location & build tour
        Fragment fragment = new NavigationFragment();
        String location = getIntent().getStringExtra("location");
        Bundle bundle = new Bundle();
        Data data = new Data(location);
        bundle.putParcelable("data", data);
        fragment.setArguments(bundle);

        //launch fragment
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.container, fragment);
        transaction.commit();
    }

    public void setupViewPager (ViewPager viewPager) {
        SectionStatePagerAdapter adapter = new SectionStatePagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new NavigationFragment(), "navFragment");
        adapter.addFragment(new QuestionFragment(), "qesFragment");
        viewPager.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        switch(item.getItemId())
        return super.onOptionsItemSelected(item);
    }
}
public class Data implements Parcelable {

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public Data createFromParcel(Parcel in) {
            return new Data(in);
        }

        public Data[] newArray(int size) {
            return new Data[size];
        }
    };

    private String tourName;
    int tourID;
    int possiblePoints;
    int stops;
    Spot[] spots;

    //while playing tour
    int points = 0;

    // Constructor
    public Data(String tour){

    }

    public String getTourName() {
        return tourName;
    }

    public void setTourName(String tourName) {
        this.tourName = tourName;
    }

    public int getTourID() {
        return tourID;
    }

    public void setTourID(int tourID) {
        this.tourID = tourID;
    }

    public int getPossiblePoints() {
        return possiblePoints;
    }

    public void setPossiblePoints(int possiblePoints) {
        this.possiblePoints = possiblePoints;
    }

    public int getStops() {
        return stops;
    }

    public void setStops(int stops) {
        this.stops = stops;
    }

    public Spot[] getSpots() {
        return spots;
    }

    public void setSpots(Spot[] spots) {
        this.spots = spots;
    }

    public int getPoints() {
        return points;
    }

    public void setPoints(int points) {
        this.points = points;
    }

    // Parcelling part
    public Data(Parcel in){
        this.tourName =  in.readString();
        this.tourID =  in.readInt();
        this.possiblePoints =  in.readInt();
        this.stops =  in.readInt();
        this.spots = in.createTypedArray(Spot.CREATOR);
        this.points = in.readInt();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.tourName);
        dest.writeInt(this.tourID);
        dest.writeInt(this.possiblePoints);
        dest.writeInt(this.stops);
        for(Spot s : spots){
            dest.writeParcelable(s, flags);
        }
        dest.writeInt(this.points);
    }


}

Thanks to @Mike M. this is solved. 感谢@MikeM。此问题已解决。

The problem was with the activity in which the fragments were hosted. 问题在于托管片段的活动。 In there I created two different NavigationFragments which I added to the activity. 在其中,我创建了两个不同的NavigationFragments,它们添加到了活动中。 The updating of the TextView happen on the wrong one. TextView的更新发生在错误的位置。

I see from another answer that there was a problem with fragment instances, but I believe you also have a problem with your Parcelable implementation. 我从另一个答案中看到片段实例存在问题,但是我相信您的Parcelable实现也有问题。

 public Data(Parcel in){ ... this.spots = in.createTypedArray(Spot.CREATOR); ... } @Override public void writeToParcel(Parcel dest, int flags) { ... for(Spot s : spots){ dest.writeParcelable(s, flags); } ... } 

These two calls need to be mirrored, and they currently are not. 这两个调用需要进行镜像,而当前不是。 Rather than iterating over the array yourself, you should use the writeTypedArray() method: 与其亲自遍历数组, writeTypedArray()使用writeTypedArray()方法:

public Data(Parcel in){
    ...
    this.spots = in.createTypedArray(Spot.CREATOR);
    ...
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    ...
    dest.writeTypedArray(spots, flags);
    ...
}

If you look at the implementations for writeTypedArray() and createTypedArray() , you'll see that part of the work is to write a flag that indicates the size of the array, so that the code knows how many instances to read out on the other side. 如果看一下writeTypedArray()createTypedArray() ,您会发现工作的一部分是编写一个指示数组大小的标志,以便代码知道在该数组上要读取多少个实例。另一边。 Your implementation does not include this step, so the two will be incompatible. 您的实现不包括此步骤,因此两者将不兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM