2015-12-07 24 views
0

我创建了一个外部类NotesView,它在我的MainActivity中扩展了View以实现。Android - 在使用setContentView时向活动添加单独的组件

该视图需要从MainActivity传递的信息,因此它的构造函数需要一个Note对象的ArrayList。

public class NotesView extends View { 

private ArrayList<Note> notes = new ArrayList<>(); 

public NotesView(Context context, ArrayList<Note> notes) { 
    super(context); 
    this.notes = notes; 
} 

在我的MainActivity,我用下面的代码来显示这样的观点:(试图在布局的设计选项卡中添加一个CustomView,因为我不能提供ArrayList的参数不工作)

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    notesView = new NotesView(this, noteList); 
    setContentView(notesView); 
} 

不幸的是,我现在无法通过布局的设计视图添加任何对象,我认为这是因为我已经使用了setContentView。我不希望以编程方式添加所有组件,有没有办法解决这个问题?

+0

为什么不使用Recyclerview/Listview。似乎完美匹配您的用例 –

+0

请参阅[Android:传递任意对象到自定义视图](http://curioustechizen.blogspot.in/2013/02/android-passing-arbitrary-object-to.html)可能帮帮我 –

回答

1

调用setContentView将替换您的布局的整个视图。这意味着,如果您拨打setContentView两次,则第一个电话添加到屏幕的任何内容都将被覆盖并且不再可访问。


有多种回答你的问题,这里是一个务实的:

里面有什么是R.layout.activity_main?让我们假设有一个FrameLayout/LinearLayout/RelativeLayout id为root

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    ViewGroup rootView = (ViewGroup) findViewById(R.id.root); 
    notesView = new NotesView(this, noteList); 
    rootView.addView(notesView); 
} 

另一种选择,你也可以把你的自定义视图有一个二传手,如果你想:

public class NotesView extends View { 

private final List<Note> notes = new ArrayList<>(); 

public NotesView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
} 

public void replaceNotes(List<Note> notes) { 
    this.notes.clear(); 
    this.notes.addAll(notes); 
} 

然后你可以在XML文件(R.layout.activity_main)加入这一观点,并调用setter方法:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    NotesView notesView = (NotesView) findViewById(R.id.notes); 
    notesView.replaceNotes(noteList); 
} 
1

您可以添加setter函数到您的NotesView类:

public class NotesView extends View { 

    private ArrayList<Note> notes; 

    public NotesView(Context context) { 
     super(context); 
    } 

    public void setNotes(ArrayList<Note> notes) { 
     this.notes = notes; 
    } 
} 

然后将其设置在主要活动:

NotesView notesView = (NotesView) findViewById(R.id.yourNotesView); 
notesView.setNotes(noteList); 

通过我建议Butterknife的方式投在布局意见没有详细的findViewByIds,声明,onXListeners等。

相关问题