尝试使用相对布局(Android)以编程方式定位时控件重叠

时间:2012-11-02 10:19:38

标签: android android-layout relativelayout

我正在尝试创建一个片段。在片段中,我打算在它旁边放置一个Spinner控件的文本视图。我尝试使用此代码。但是,Spinner始终位于屏幕左侧的textview上。任何人都可以提出可能存在的问题吗?

代码:

public class FragmentTest extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    RelativeLayout view = (RelativeLayout)inflater.inflate(R.layout.ll2, null);
    RelativeLayout lref = (RelativeLayout)view.findViewById(R.id.ll2ll);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(lref.getLayoutParams());

    lp.addRule(RelativeLayout.ALIGN_LEFT);

    RelativeLayout rl = new RelativeLayout(getActivity());

    TextView tv = new TextView(getActivity());
    tv.setId(1);
    tv.setLayoutParams(lp); 
    tv.setText("My ");


    rl.addView(tv, lp);

    Spinner s = new Spinner(getActivity());
    lp.addRule(RelativeLayout.RIGHT_OF, tv.getId());
    s.setId(2);
    String currencyData[] = {"USD",
            "EUR","INR"
    };

    ArrayAdapter<Object> currencyAdapter; currencyAdapter = new ArrayAdapter<Object>(getActivity(), android.R.layout.simple_spinner_item, currencyData);
    currencyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    s.setAdapter(currencyAdapter);

    rl.addView(s,lp);
    return rl;
}
}

XML文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="fill_parent"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:layout_marginTop="10sp"
android:isScrollContainer="true"
android:orientation="horizontal" >

<RelativeLayout
    android:id="@+id/ll2ll"
    android:layout_width="140dp"
    android:layout_height="50dp"
    android:textSize="@dimen/font_size" />

</RelativeLayout>

2 个答案:

答案 0 :(得分:2)

当视图从XML中膨胀时,您将无法正确获取LayoutParams。尝试使用new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

答案 1 :(得分:0)

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(lref.getLayoutParams());

你的问题是这个,你不能使用相同的布局参数来添加所有布局和修改lp。 因为在初始化所有布局之后使用lp,这意味着您对所有布局使用相同的参数spinner和textview。

尝试为所有布局使用不同的布局参数

RelativeLayout.LayoutParams lp

RelativeLayout.LayoutParams lptextview

RelativeLayout.LayoutParams lpspinner

所有人

如果您的问题得到解决,请将我的答案标记为正确