为什么将常量传递给Bundle对象putString()方法?

时间:2017-04-07 00:21:05

标签: java android

我正在看一个教程,并且不明白为什么他决定传入常量。在传递数据的下一个活动中会产生相同的常量,为什么会这样?到目前为止我所知道的常量的唯一用途是像pi和其他数学常量这样的东西。

ListActivity.java

public class ListActivity extends AppCompatActivity implements DerpAdapter.ItemClickCallback {
private static final String BUNDLE_EXTRAS = "BUNDLE_EXTRAS";
private static final String EXTRA_QUOTE = "EXTRA_QUOTE";
private static final String EXTRA_ATTR = "EXTRA_ATTR";

private RecyclerView recyclerView;
private DerpAdapter adapter;
private ArrayList listData;

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

    listData = (ArrayList) DerpData.getListData();

    recyclerView = (RecyclerView) findViewById(R.id.rec_list);
    //LayoutManager controls if you are using Linear, staggard etc. It controls the views.
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    adapter = new DerpAdapter(DerpData.getListData(), this);
    recyclerView.setAdapter(adapter);
    adapter.setItemClickCallback(this);
}

@Override
public void onItemClick(int p) {
    ListItem item = (ListItem) listData.get(p);

    Intent i = new Intent(this, DetailActivity.class);

    Bundle extras = new Bundle();
    extras.putString(EXTRA_QUOTE, item.getTitle());
    extras.putString(EXTRA_ATTR, item.getSubTitle());
    i.putExtra(BUNDLE_EXTRAS, extras);

    startActivity(i);
}


@Override
public void onSecondaryIconClick(int p) {
    ListItem item = (ListItem) listData.get(p);
    //update our data
    if (item.isFavourite()){
        item.setFavourite(false);
    } else {
        item.setFavourite(true);
    }
    //pass new data to adapter and update
    adapter.setListData(listData);
    adapter.notifyDataSetChanged();
}

DetailActivity.java

public class DetailActivity extends AppCompatActivity {
private static final String BUNDLE_EXTRAS = "BUNDLE_EXTRAS";
private static final String EXTRA_QUOTE = "EXTRA_QUOTE";
private static final String EXTRA_ATTR = "EXTRA_ATTR";


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

    Bundle extras = getIntent().getBundleExtra(BUNDLE_EXTRAS);

    ((TextView)findViewById(R.id.lbl_quote_text)).setText(extras.getString(EXTRA_QUOTE));
    ((TextView)findViewById(R.id.lbl_quote_attribution)).setText(extras.getString(EXTRA_ATTR));
}

0 个答案:

没有答案