从另一个类更新TableLayout

时间:2017-04-21 16:40:38

标签: android

我对android很新,我一直在阅读stackeroverflow,我们需要在从另一个类更新TableLayout时传递Context。但我不是试图直接从另一个类更新TableLayout;我试图通过调用MainActivity中的方法来更新它。并且此方法具有所有更新代码。

这就是我所拥有的:

public class MainActivity extends Activity {

public void addTableRow(String company, Integer shares, float p, float f) {

     TableLayout tl = (TableLayout) findViewById(R.id.tablelayout);
     TableRow tr = new TableRow(this);

     //does a bunch of stuff here
     //then does some formatting

     companyName.setText(company);
     companyShares.setText(shares.toString());
     dailyChange.setText(String.format("%.2f", p));
     dailyChangeToPortfolio.setText(String.format("%.2f", f));

     tr.addView(companyName);
     tr.addView(companyShares);
     tr.addView(dailyChange);
     tr.addView(dailyChangeToPortfolio);

     tl.addView(tr);
}

}

在我的其他课程中

public class UpdateStock {

    public void startUpdate(){
        MainActivity m = new MainActivity();
        m.addTableRow("CSCO", 10, 5.555f, 6.666f);
    }
}

但它对我有误。任何让这个工作起来的建议都会很棒。

1 个答案:

答案 0 :(得分:0)

您可以使用Intent将数据传递到新的Activity:

public static class MyRowData implements Serializable {

    String company;
    Integer shares;
    float p;
    float f;

    public MyRowData(String company, Integer shares, float p, float f) {
        this.company = company;
        this.shares = shares;
        this.p = p;
        this.f = f;
    }
}

public class UpdateStock {

    public void startUpdate(){
        MyRowData rowData = new MyRowData("CSCO", 10, 5.555f, 6.666f);
        Intent intent = new Intent(getActivity(), MainActivity.class);
        intent.putExtra("MY_DATA", rowData);
        startActivity(intent);
    }
}

public class MyActivity extends Activity {

    MyRowData getRowData()
    {
        return (MyRowData)getIntent().getSerializableExtra("MY_DATA");
    }
}
相关问题