0

我想知道如何根据条件更改 xml 文件的布局。所以可以说我们有这样的布局..

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"

>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="@drawable/app_background"
 android:padding="5dip"
 >

<ListView android:id="@+id/xlist"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:cacheColorHint="#00000000"

            android:divider="@drawable/listdivider"
            android:dividerHeight="19dp"

           />
  <TextView 
              android:layout_width="fill_parent"
              android:background="@drawable/listdivider"
              android:layout_height="19dp"
              android:visibility="gone"
             android:id="@+id/dividerline"
              />
  <ListView android:id="@+id/ylist"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:cacheColorHint="#00000000"
             android:divider="@drawable/listdivider"
            android:dividerHeight="19dp"

           />
</LinearLayout>
</LinearLayout>

因此,您将两个变量设置为列表视图,并且基于 xml,“xlist”将出现在“ylist”之前。但是对于我的代码,如果满足某个条件,我想切换此视图的顺序。那么我将如何切换顺序,以便如果满足某个条件,“ylist”将出现在“xlist”上方?

4

2 回答 2

3

An easy way to do that is to put each view in its own xml file. Then at runtime attach them to the linearLayout in the desired order.

Say your layout file is: main.xml and you have list_a.xml, list_b.xml, and textview.xml

in your activity:

@Override

public void onCreate(Bundle bundle) {
 Super.onCreate(bundle);
 setContentView(R.layout.main);
 LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
 LayoutInflater inflater = getLayoutInflater();
 if (condition) {
 inflater.inflate(R.layout.list_a, layout);
 inflater.inflate(R.layout.textview, layout);
 inflater.inflate(R.layout.list_b, layout);


} else { 
     inflater.inflate(R.layout.list_b, layout);
 inflater.inflate(R.layout.textview, layout);
 inflater.inflate(R.layout.list_a, layout);
 }
 }
于 2013-01-23T15:29:51.933 回答
0

从来没有这样做过,但这应该有效:

public void switchViewOrder(final ViewGroup parent, final int view1Id, final int view2Id) {

    View view1 = null;
    int view1pos = -1;
    View view2 = null;
    int view2pos = -1;

    int count = parent.getChildCount();
    for(int i = 0; i < count; i++) {
        View cur = parent.getChildAt(i);
        if (view1Id == cur.getId()) {
            view1 = cur;
        } else if (view2Id == cur.getId()) {
            view2 = cur;
        }
    }

    parent.removeViewAt(view1pos);
    parent.removeViewAt(view2pos);

    parent.addView(view1, view2pos);
    parent.addView(view2, view1pos);
}

我让你添加适当的空值和类似的检查。

于 2013-01-23T15:27:17.977 回答