[英]Add a custom view to main view programatically in android
I have two views in an Fragment. 我在一个片段中有两个视图。 First view is main view declared in onCreateView() named as weather.xml and second view is a view which is in project res/layout/weather_column.xml.
第一个视图是在onCreateView()中声明的主视图,命名为weather.xml,第二个视图是在项目res / layout / weather_column.xml中的视图。
I want to add weather_column.xml to weather.xml programatically using a loop. 我想使用循环以编程方式将weather_column.xml添加到weather.xml。
Finally, it should be like ... 最后,它应该像...
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class WeatherFragment2 extends Fragment {
private static final String TAG = WeatherFragment2.class.getSimpleName();
LinearLayout bottemLL;
LayoutInflater layoutInflater;
LayoutParams params ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
params = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
params.gravity = Gravity.RIGHT;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.weather, container, false);
layoutInflater = inflater;
LinearLayout bottemLL = (LinearLayout) v.findViewById(R.id.bottem_ll);
addView(bottemLL);
return v;
}
private void addView(LinearLayout bottemLL2) {
View v ;
for (int i = 0; i < 6; i++) {
Log.e(TAG, "i=========="+i);
v = layoutInflater.inflate(R.layout.weather_column, null);
bottemLL2.addView(v, params);
}
}
}
But i am able to add view only once after doing loop. 但是我只能在执行循环后添加一次视图。
Please help me on this. 请帮我。 Thank you.
谢谢。
我认为您总是添加相同的视图,应该在循环内创建一个新的View并将其充气。
Try this : 尝试这个 :
private void addView(LinearLayout bottemLL2)
{
View v ;
v = layoutInflater.inflate(R.layout.weather_column, null);
for (int i = 0; i < 6; i++)
{
Log.e(TAG, "i=========="+i);
bottemLL2.addView(v, params);
}
}
The code what you posted indeed adds 6 different view to your LinearLayout. 您发布的代码确实为您的LinearLayout添加了6种不同的视图。 So that part should be fine.
所以那部分应该没问题。
I guess the problem is that they too big, so they cant fit in the same container. 我猜问题是它们太大了,因此它们不能放入同一容器中。 Try to modify the underlying XML-s.
尝试修改基础XML-s。
Could you send your layout files? 您可以发送布局文件吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.