如何使用接口正确实现多态?

时间:2019-03-04 17:18:12

标签: java android interface model polymorphism

我有2个模型类(Data,Title),它们包含相同的字段: 字符串dataID。我想通过接口实现同时获得这两个ID。

我将Title模型通过Bundle传递给另一个Activity,将Data模型通过Bundle传递给同一活动(只是创建该活动的新实例并重置信息)。

我希望我的两个模型类都使用String getSharedId();方法实现SharedID接口。

如何从不同的型号获得不同的ID?我只需要在ViewModelFactory构造函数中放入一个参数,它应该是String。

public class Data implements SharedId,Parcelable {

private String text;
private String textHeader;
private int viewType;
private String mainId;
private String dataID;

public Data() { }

public String getDataID() {
    return dataID;
}

public void setDataID(String dataID) {
    this.dataID = dataID;
}

public String getText() {return (String) trimTrailingWhitespace(text); }

public void setText(String text) {
    this.text = (String) trimTrailingWhitespace(text);
}

public String getTextHeader() {
    return (String) trimTrailingWhitespace(textHeader);
}

public void setTextHeader(String textHeader) {
    this.textHeader = textHeader;
}

public int getViewType() {
    return viewType;
}

public void setViewType(int viewType) {
    this.viewType = viewType;
}

public String getMainId() {
    return mainId;
}

public void setMainId(String mainId) {
    this.mainId = mainId;
}

protected Data(Parcel in) {
    text = in.readString();
    textHeader = in.readString();
    viewType = in.readInt();
    mainId = in.readString();
    dataID = in.readString();
}

@Override
public String toString() {
    return "Data{" +
            "order=" +
            ", text='" + text + '\'' +
            ", textHeader='" + textHeader + '\'' +
            ", viewType=" + viewType +
            '}';
}

@SuppressWarnings("StatementWithEmptyBody")
public static CharSequence trimTrailingWhitespace(CharSequence source) {
    if (source == null) {
        return "";
    }
    int i = source.length();
    // loop back to the first non-whitespace character
    while (--i >= 0 && Character.isWhitespace(source.charAt(i))) {
    }
    return source.subSequence(0, i + 1);
}

public static final Creator<Data> CREATOR = new Creator<Data>() {
    @Override
    public Data createFromParcel(Parcel in) {
        return new Data(in);
    }

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

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

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(text);
    dest.writeString(textHeader);
    dest.writeInt(viewType);
    dest.writeString(mainId);
    dest.writeString(dataID);
}

@Override
public String getSharedDataId() {
    return getDataID();
}

}

public class Title implements SharedId,Parcelable {

private String dataID;
private String title;

public Title() { }

protected Title(Parcel in) {
    dataID = in.readString();
    title = in.readString();
}

public String getDataID() {
    return dataID;
}

public void setDataID(String dataID) {
    this.dataID = dataID;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public static final Creator<Title> CREATOR = new Creator<Title>() {
    @Override
    public Title createFromParcel(Parcel in) {
        return new Title(in);
    }

    @Override
    public Title[] newArray(int size) {
        return new Title[size];
    }
};

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

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(dataID);
    dest.writeString(title);
}

@NonNull
@Override
public String toString() {
    return "Title{" +
            "dataID='" + dataID + '\'' +
            ", titleOrder=" +
            ", title='" + title + '\'' +
            '}';
}

@Override
public String getSharedDataId() {
    return getDataID();
}
}

还有我的DetailActivity代码,我已经成功完成了传递id的任务,但是我需要这样做是通过低谷接口的:(因此,请帮我的朋友们,不胜感激!

public class DetailActivity extends AppCompatActivity implements
    DetailAdapter.OnDialogClickListener,
    DetailAdapter.OnDetailClickListener {
private static String id;
private String parentId;
private Data data;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

    TextView tvToolbarTitle = findViewById(R.id.title_toolbar_detail);
    tvToolbarTitle.setSelected(true);
    findViewById(R.id.btn_back).setOnClickListener(v -> finish());

    ArrayList<SharedId> sharedIds = new ArrayList<>();
    sharedIds.add(new Title());
    sharedIds.add(new Data());
    for (SharedId sharedId : sharedIds){
        System.out.println(sharedId.getSharedDataId());
    }

    Bundle bundle = getIntent().getExtras();

    if (bundle != null) {
        Title model = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
        Data childModel = bundle.containsKey("idDetail") ? bundle.getParcelable("idDetail") : null;
    }
    if (bundle != null) {
        Title model = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
        Data childModel = bundle.containsKey("idDetail") ? bundle.getParcelable("idDetail") : null;
        String parentId = bundle.getString("mainScreenId");
        if (parentId != null) {
            this.parentId = parentId;
        }
        if (model != null) {
            this.id = model.getDataID();
            tvToolbarTitle.setText(model.getTitle());
        }
        if (childModel != null) {
            this.id = childModel.getDataID();
            tvToolbarTitle.setText(childModel.getTextHeader());
        }
    }
    RecyclerView recyclerView = findViewById(R.id.rv_detail);
    DetailAdapter adapter = new DetailAdapter(this, this);
    recyclerView.setAdapter(adapter);
    // TODO: 3/1/19 change it to single ID // DetailViewModelFactory(); // id != null ? id : parentId
    DetailViewModelFactory detailViewModelFactory = new DetailViewModelFactory(id != null ? id : parentId);
    DetailActivityViewModel viewModel = ViewModelProviders.of(this, detailViewModelFactory).get(DetailActivityViewModel.class);
    FirebaseListLiveData<Data> liveData = viewModel.getLiveDataQuery();
    liveData.observe(this, adapter::setNewData);
}

@Override
public void onDialogClicked(@NonNull String text) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(HtmlCompat.fromHtml(text, 0, null, new HandlerHtml()));
    builder.setPositiveButton("Ok", null);
    builder.show();
}

   @Override
    public void onDetailClicked(Data data) {
     Intent intent = new Intent();
    DetailActivity.open(DetailActivity.this);
    intent.putExtra("idDetail", data);
    intent.putExtra("mainScreenId", id);
    startActivity(intent);
    }
    public static void open(@NonNull Context context) {
    context.startActivity(new Intent(context, InfoActivity.class));
   }
  }

1 个答案:

答案 0 :(得分:0)

我发现有些不同,但是可行的解决方案!

我创建一个界面

public interface SharedId {
 String getSharedDataId();
 String getHeader();
}

我的两个模型类都是Data + Title实现的接口和方法。     在DetailActivity中,我创建了2个字符串。     private String mainId;     私有字符串detailId; 然后通过绑定的模型类传递ids

`SharedId mainId = new Title();
    SharedId detailId = new Data();
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        mainId = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
        detailId = bundle.containsKey("idDetail") ? 
     bundle.getParcelable("idDetail") : null;
    }
    if (mainId != null) {
        this.detailId = mainId.getSharedDataId();
        tvToolbarTitle.setText(mainId.getHeader());
    }
    if (detailId != null) {
        this.mainId = detailId.getSharedDataId();
        tvToolbarTitle.setText(detailId.getHeader());
    }

并传入我的ViewmodelFactory

 DetailViewModelFactory detailViewModelFactory =
            new DetailViewModelFactory(this.detailId != null ?
            this.detailId : this.mainId);