[英]How to add any view programatically using java code only?
i hope you are fine.我希望你们都很好。 im new in java, and what i want is to add any view, i determine it using java code only, i did that in dialog, i added edit text to alert dialog using this code :
我是 Java 新手,我想要添加任何视图,我仅使用 Java 代码确定它,我在对话框中这样做,我使用以下代码将编辑文本添加到警报对话框:
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_TRADITIONAL);
alert.setTitle("Title");
final EditText myedit = new EditText(MainActivity.this);
myedit.setHint("Type something");
myedit.setLayoutParams
(new LinearLayout.LayoutParams
(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));
final AlertDialog dialog = alert.create();
dialog.show();
and this work 100% with me, i got edittext in the Dialog, like this :这对我来说是 100% 的工作,我在对话框中得到了编辑文本,如下所示:
and now i can't get another view by using this way in the MainActivity view:现在我无法通过在 MainActivity 视图中使用这种方式获得另一个视图:
for example this code here i tried it without get anything :例如这里的代码我试了一下没有得到任何东西:
final LinearLayout linear1 = new LinearLayout(this);
linear1.setOrientation(LinearLayout.HORIZONTAL);
linear1.setBackgroundColor(Color.white);
LinearLayout.LayoutParams layoutForInner = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linear1.setLayoutParams(layoutForInner);
final ListView listview1 = new ListView(this);
listview1.setLayoutParams
(new LinearLayout.LayoutParams
(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));
linear1.addView(listview1);
please Help me solving this, if it is not possible please give me alternative to this way, for adding/creating views from .java only without need .xml请帮我解决这个问题,如果不可能,请给我这种方式的替代方法,以便仅从 .java 添加/创建视图而不需要 .xml
For This to work you must use the Dialog insted of AlertDialog class.为此,您必须使用 AlertDialog 类的 Dialog insted。
Dialog dialog = new Dialog(getActivity(),android.R.style.Theme_Black_NoTitleBar_Fullscreen);
dialog.setContentView(R.layout.your_contentview);
After defining dialog you must define views in your dialog定义对话框后,您必须在对话框中定义视图
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, );
LinerLayout layout = new LinearLayout(context, params);
dialog.addView(loadMsg, params);
final ListView listview1 = new ListView(this);
listview1.setLayoutParams (new LinearLayout.LayoutParams (android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));
linear1.addView(listview1);
dialog.setView(layout);
dialog.show();
So to sum it up //所以总结一下//
1.define a dialog 1.定义一个对话框
2.make linear layout in it 2.在其中进行线性布局
3.add listview in it. 3.在其中添加列表视图。 call the set view method.
调用设置视图方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.