【发布时间】:2016-08-17 01:44:19
【问题描述】:
我正在 android 中创建自定义视图(我想使用 Java 代码动态地执行此操作)。我将相对布局扩展到该类。当我为这个相对布局使用滚动视图时,它不起作用(不滚动,只显示相对布局中的一个按钮)。
但是当我将相对布局更改为线性布局并将线性布局方向设置为垂直时,它可以工作并且我可以滚动布局。
这是自定义布局类:
import android.content.Context;
import android.graphics.Color;
import android.widget.Button;
import android.widget.RelativeLayout;
import java.util.ArrayList;
public class CustomLayout extends RelativeLayout {
public static ArrayList<Button> btnList;
int btnHeight = pxFromDp(getContext(), 70);
public CustomLayout(Context context) {
super(context);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setLayoutParams(params);
//setOrientation(VERTICAL); ---> for LinearLayout
btnList = new ArrayList<>();
}
public void addButton(String buttonText, int id) {
Button btn = new Button(getContext());
if(id > 0)
btn.setY(btnList.get(id - 1).getBottom());
else
btn.setY(0);
btn.setText(buttonText);
btn.setBackgroundColor(Color.GRAY);
btnList.add(btn);
addView(btnList.get(id), id,new LayoutParams(LayoutParams.MATCH_PARENT, btnHeight));
}
//just convert dpi to pixel
public static int pxFromDp(final Context context, float dp) {
return (int) (dp * context.getResources().getDisplayMetrics().density);
}
}
这是我在 Scroll View 中对此类的使用:
import android.app.Activity;
import android.os.Bundle;
import android.widget.ScrollView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CustomLayout csLayout = new CustomLayout(this);
for (int i = 0 ; i < 20 ; i++) {
csLayout.addButton("Button " + i, i);
}
ScrollView sv = new ScrollView(this);
sv.addView(csLayout);
setContentView(sv);
}
}
请记住,此自定义视图适用于扩展线性布局。
我也应该如何为相对布局工作?
【问题讨论】:
标签: android android-layout layout android-linearlayout android-relativelayout